Java Map Hidden Superpowers

Aviral Ahuja
2 min readMay 21, 2023

--

that you must know …

Maps are an integral part of Java Collection Framework and has methods that can make our code more readable. Lets start:-

  • MERGE
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction)

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. Lets understand this with example
We will start by preparing data

        Map<String, List<String>> fruits = new HashMap<>();
fruits.put("SUMMER", List.of("Watermelon", "musk melon", "litchi"));
fruits.put("WINTER", List.of("orange", "guava", "pears"));

Map<String, List<String>> vegetables = new HashMap<>();
fruits.put("SUMMER", List.of("bitter gaurd", "capsicum", "beans"));
fruits.put("WINTER", List.of("carrot", "cauliflower", "cabbage"));
fruits.put("ALL_SEASON", List.of("potato", "onion", "tomato"));

Requirement:- We want fruits and vegetables combined.

Traditional Way:-

Map<String, List<String>> fruitsAndVegetables = new HashMap<>(fruits);
vegetables.forEach((key, value) -> {
if (fruitsAndVegetables.containsKey(key)) {
fruitsAndVegetables.get(key).addAll(value);
} else {
fruitsAndVegetables.put(key, value);
}
});

using Merge:-

Map<String, List<String>> fruitsAndVegetables = new HashMap<>(fruits);
vegetables.forEach((key, value) -> fruitsAndVegetables.merge(key, value, (o, n) -> {
o.addAll(n);
return o;
}));
  • ComputeIfAbsent
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
It returns the current (existing or computed) value associated with the specified key, or null if the computed value is null.
Its Primarily useful with Concurrent map Implementations like ConcurrentHashMap which guarantees atomicity.

Lets try to implement a singleton resource factory and see it in practice.

public class ResourceFactory {

Map<String ,Resource> resources = new ConcurrentHashMap<>();

public Resource get(String key){
return resources.computeIfAbsent(key, (k) -> new Resource(k));
}

public Resource getTraditional(String key){
if(!resources.containsKey( key)){
synchronized (key){
if(!resources.containsKey(key)){
resources.put(key, new Resource(key));
}
}
}
return resources.get(key);
}

@AllArgsConstructor
private static class Resource{
String key;
}
}

As we can clearly see, get method is more efficient and readable than getTraditional.

Bonus:- remove all keys with null values

map.values().removeAll(Collections.singleton(null));

If you find this Article interesting, don’t forget to follow for more.

--

--

Aviral Ahuja

Software Engineer | JAVA | Spring | Write about everything technical