patternjavaMinor
Increment all values in a Map by 1
Viewed 0 times
valuesincrementmapall
Problem
What's the neatest way to increment all values in a
This doesn't look too messy to me but I'm wondering if people like seeing lambdas more.
HashMap by 1? The map is `, but the key doesn't matter as every value will be incremented.
Is it "cleaner" to use lambdas with forEach/compute`/etc. or just loop through the entries?HashMap map = mobCounter.get(mob);
for (Entry e : map.entrySet()) {
map.put(e.getKey(), e.getValue() + 1);
}This doesn't look too messy to me but I'm wondering if people like seeing lambdas more.
Solution
You must not modify the keys of a
Instead of the
If you have some kind of
Using lambdas, your code would look like:
This looks very nice to me. It cannot get any shorter.
HashMap while iterating over it. You are just lucky it worked.Instead of the
put(...), write e.setValue(e.getValue() + 1).If you have some kind of
Multiset available (e.g. when you are using Guava), you could replace your HashMap with a Multiset, which will make your intention clearer.Using lambdas, your code would look like:
map.replaceAll((k, v) -> v + 1);This looks very nice to me. It cannot get any shorter.
Code Snippets
map.replaceAll((k, v) -> v + 1);Context
StackExchange Code Review Q#148218, answer score: 8
Revisions (0)
No revisions yet.