Here is one Java idiom I am happy to see go away with the tools made available in Java 8. In this scenario we have a Map with mutable values for which not all keys are known at creation time.
Before Java 8, the way to add a mapping would look like this:
private final Map< String, List< String > > map = new HashMap<>();
public void addValue(String key, String value) {
List valueList = map.get(key);
if (valueList == null) {
valueList = new ArrayList<>();
map.put(key, valueList);
}
valueList.add(value);
}
The equivalent logic with Java 8 is:
public void addValue(String key, String value) {
map.computeIfAbsent(key, v -> new ArrayList<>()).add(value);
}
If the Map values are immutable, the following also works:
private final Map< String, String > map = new HashMap<>();
public void addValue(String key, String value) {
map.merge(key, value, (v1, v2) -> value);
}
No comments:
Post a Comment