Once in a while I come across the task where I have a list of Items that I want to filter and afterwards store in a map. Usually the key is a property of the Item: anItem.name -> anItem
In the usual Java way this looked like the following:
Map<String, Stuff> map = new HashMap<>(); for (Stuff s : list) { if (!s.name.equals("a")){ map.put(s.name, s); } }
Nothing really special, but it somehow doesn’t look too nice. Yesterday I thought: in Scala I would emit tuples and call .toMap
. Isn’t that also possible with Java 8 Streams? And indeed it is:
Map<String, Item> map = l.stream() .filter(s -> !s.name.equals("a")) .collect(toMap(s -> s.name, s -> s)); // toMap is a static import of Collectors.toMap(...)
This looks compact and readable!
If you don’t like s -> s
, just use identity() function of the Function class. Actually I do not like static imports very much as as they make the code less readable, but in this case I would decide for static imports.
Map<String, Item> map = l.stream() .filter(s -> !s.name.equals("a")) .collect(toMap(s -> s.name, identity())); // toMap and identity are imported statically