Skip to content

Instantly share code, notes, and snippets.

@dongjinleekr
Created February 7, 2017 07:52
Show Gist options
  • Save dongjinleekr/f5c5e6243d44d8655096a1a5ea21330a to your computer and use it in GitHub Desktop.
Save dongjinleekr/f5c5e6243d44d8655096a1a5ea21330a to your computer and use it in GitHub Desktop.
Accumulating Map Values in Java 8
// Uses a function instance with internal state, along with mapping the map values only.
// see: http://stackoverflow.com/questions/23213891/how-to-map-values-in-a-map-in-java-8
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.function.Function;
import static java.util.stream.Collectors.toMap;
// A map instance to be accumulated
Map<String, Integer> before = new ImmutableMap.Builder<String, Integer>()
.put("A", 1)
.put("B", 2)
.put("C", 3)
.build();
// Accumulator function with its internal state
Function<Integer, Integer> f = new Function<Integer, Integer>() {
private int acc = 0;
@Override
public Integer apply(Integer integer) {
acc += integer;
return acc;
}
};
// The result
Map<String, Integer> after = before.entrySet()
.stream()
.collect(toMap(Map.Entry::getKey, entry -> f.apply(entry.getValue())));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment