I have got back to writing code in Java (coming from python), and it is frustrating to see that HashMap in Java don’t have a default HashMap wrapper shipped in. Java has always been verbose, but I have particularly started liking Java8. I remember in the older versions, just extracting an integer array from a string like 1 2 3 4 5 6
would be so difficult. Now, there is a real nice stream, map, collect API that lets you do all this in one line.
String test = "1 2 3 4 5 6";
List<Integer> arr = Arrays.stream(test.split(" ")).map(x -> Integer.parseInt(x)).collect(Collectors.toList());
Oh well, coming back to the point — I don’t want to keep checking if the map contains a key. I don’t think writing it again and again is productive too. Here is a helper util that I always use to help deal with default HashMap problem:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public V get(Object k) {
return containsKey(k) ? super.get(k) : defaultValue;
}
}
Hope it helps, back to writing verbose code :)