Skip to content

Instantly share code, notes, and snippets.

@sandeepkv93
Created February 18, 2025 16:36
Show Gist options
  • Save sandeepkv93/d8f9a0287829ec019e17f19853357a86 to your computer and use it in GitHub Desktop.
Save sandeepkv93/d8f9a0287829ec019e17f19853357a86 to your computer and use it in GitHub Desktop.

Advanced HashMap Methods in Java - Use Cases & Examples

1. getOrDefault(K key, V defaultValue)

Use Cases:

  • Counting occurrences efficiently.
  • Handling missing keys.
  • Providing default responses.

Example: Word Frequency Counter

Map<String, Integer> wordCount = new HashMap<>();
String[] words = {"apple", "banana", "apple", "orange"};

for (String word : words) {
    wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
System.out.println(wordCount); // {apple=2, banana=1, orange=1}

2. putIfAbsent(K key, V value)

Use Cases:

  • Avoiding overwriting existing data.
  • Initializing a key if missing.
  • Thread-safe initialization.

Example: Initializing a List in a Map

Map<String, List<String>> categoryMap = new HashMap<>();
categoryMap.putIfAbsent("fruits", new ArrayList<>());
categoryMap.get("fruits").add("apple");
System.out.println(categoryMap); // {fruits=[apple]}

3. replace(K key, V value)

Use Cases:

  • Updating only if the key exists.
  • Avoiding accidental insertions.

Example: Updating User Scores

Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 50);
scores.replace("Alice", 60);
scores.replace("Bob", 40); // Won't insert Bob
System.out.println(scores); // {Alice=60}

4. merge(K key, V value, BiFunction<V,V,V> remappingFunction)

Use Cases:

  • Counting occurrences.
  • Aggregating values.
  • Combining logs/messages.

Example: Merging Vote Counts

Map<String, Integer> votes = new HashMap<>();
String[] candidates = {"Alice", "Bob", "Alice", "Bob", "Alice"};

for (String candidate : candidates) {
    votes.merge(candidate, 1, Integer::sum);
}
System.out.println(votes); // {Alice=3, Bob=2}

5. compute(K key, BiFunction<K,V,V> remappingFunction)

Use Cases:

  • Updating values dynamically.
  • Transforming data.
  • Conditional value modification.

Example: Adjusting Discounted Prices

Map<String, Double> priceMap = new HashMap<>();
priceMap.put("Laptop", 1000.0);
priceMap.compute("Laptop", (k, v) -> v * 0.9);
System.out.println(priceMap); // {Laptop=900.0}

6. computeIfAbsent(K key, Function<K,V> mappingFunction)

Use Cases:

  • Lazy initialization.
  • Caching values.
  • Fetching missing data.

Example: Initializing Nested Lists

Map<String, List<Integer>> graph = new HashMap<>();
graph.computeIfAbsent("A", k -> new ArrayList<>()).add(1);
graph.computeIfAbsent("B", k -> new ArrayList<>()).add(2);
System.out.println(graph); // {A=[1], B=[2]}

7. computeIfPresent(K key, BiFunction<K,V,V> remappingFunction)

Use Cases:

  • Modifying values only if key exists.
  • Removing elements conditionally.

Example: Deducting Balance

Map<String, Integer> accountBalance = new HashMap<>();
accountBalance.put("User1", 100);
accountBalance.computeIfPresent("User1", (k, v) -> v - 10);
System.out.println(accountBalance); // {User1=90}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment