Advanced HashMap Methods in Java - Use Cases & Examples
1. getOrDefault(K key, V defaultValue)
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)
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)
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)
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)
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)
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)
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}