Skip to content
Advertisement

Map List to Map with additional transformation

I need to convert a list of objects to a map of sets of one of the objects’ property and I’d like to use Java streams for that.

For example there is a List<Dog> and I’d like to convert it to a HashMap where key is dog age and value is Set of breeds.

JavaScript

I can create Map<Integer, Set<Dog>> dogsByAge a by using this statement.

JavaScript

However I need Map<Integer, Set<String>> breedsByAge

Is that possible using streams?

Advertisement

Answer

The following should meet the requirement:

JavaScript

Demo:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement