Java 8 Streams: Collecting items into a Map of (Key, Item)

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

In the usual Java way this looked like the following:

Map<String, Stuff> map = new HashMap<>();
for (Stuff s : list) {
    if (!"a")){
        map.put(, 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 =
    .filter(s -> !"a"))
    .collect(toMap(s ->, 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 =
    .filter(s -> !"a"))
    .collect(toMap(s ->, identity())); // toMap and identity are imported statically

Leave a Reply

Your email address will not be published.