Every developer who tried to program on Python is charmed by its convenient syntax and feeling that language understands you from half of the word. However, we are not always programming in the language that has the most comfortable syntax either because of performance or existing codebase or other reasons. When you switch from Python you may be missing some features that work differently in Java. And today I want to show how to mimic Python defaultdict: defaultdict(list)
or defaultdict(set)
in Java. For example, we need to sort Strings into Sets by the length of a String. Without further ado, we are diving into the Python code snippet…:
# we will collect Strings to Sets by a length of a String
map = collections.defaultdict(set)
for str in strings:
map[len(str)].add(str)
…and then to similar Java code:
var map = new HashMap<Integer, HashSet<String>>();
for (String str : strings) {
map.computeIfAbsent(str.length(), (key) -> new HashSet<String>()).add(str);
}
We’ve used map.computeIfAbsent(K key, Function mappingFunction)
with lambda expression as mappingFunction
creating HashSet
. It is a very safe bet because computeIfAbsent
returns either existing in Map
value (HashSet
) or newly created with lambda expression HashSet
. This provides us with capability to sequentially add a String with HashSet.add(str)
. It is more secure than the equivalent Map.putIfAbsent(key, new HashSet<String>())
which, while does return existing value if it is already in the Map, otherwise will add new HashSet
and return null
when a key is not in the Map
. That will imply get into NullPointerException
.
Taking into account the strong typing of Java we received a decently short solution that with the elegant one-liner at least eliminates cumbersome code of if() statement
checks of Map.containsKey(), Map.get(key) == null
and creation of HashSet
. While we have not got a similar sweetness of syntax as in Python defaultdict, today we squeezed maximum from Java and will proceed chasing Python in the next series… 😄
Making nod of the head to Oracle for handy documentation on Map
: https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Map.html