Skip to content
Advertisement

Java stream/collect: map one item with multiple fields to multiple keys

I have the following code that I’d like to try to write using the java collectors.

Given 2 attributes (firstname and lastname) of a person, I’d like to get a map containing the unique firstname or lastname as a key, and the list of the corresponding persons.

Here’s a set of data :

JavaScript

Output (as expected) is the following :

JavaScript

And the code to populate the map :

JavaScript

I can’t figure out how I can get either the firstname or the lastname as a key (not like in Group by multiple field names in java 8). Do I have to write my own collector?

Advertisement

Answer

You can use Stream.flatMap() and Collectors.groupingBy() with Collectors.mapping():

JavaScript

This uses flatMap to expand all names (first and last) to their Person object and collects it afterwards.

Alternatively using Java 9 or above you could use Collectors.flatMapping():

JavaScript

But I don’t think that this is more readable.

Advertisement