Nooblhu Nooblhu - 22 days ago 7
Java Question

Adding repetead String keys to map using foreach where value is the number of repetitions

In my process to learn Java 8 forEach, I'm trying to change this code:

Integer counter;
for(String s : stringList) {
counter = myMap.get(s);

if(counter == null) {
myMap.put(s, 1);
}
else {
myMap.put(s, counter + 1);
}
}


As you can see, the idea is that if the String is absent, it's added as key and the value is set to 1.
When the key is present, counter is equal to the latest value and then the value is replace with counter + 1.

I tried this:

stringList.forEach(s-> myMap.putIfAbsent(s,1));


but that just covers half the job.

I know that methods like computeIfAbsent and computeIfPresent exist, but after the key, a function is required but I'm not sure what. Can't change the value to counter since it should be final. Seems like there isn't putIfPresent...

Is it possible to do this using forEach and a lambda expression or should I just keep it like that?

Answer

You can use the merge function on the map. It takes a key, a value, and a function that will be called if the key existed from before.

You can use it like this:

stringList.forEach(s -> myMap.merge(s, 1, (oldValue, newValue) -> oldValue + 1));

You can also return null from the lambda if you want to remove the key.

Full documentation here:

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-