8

I have following class:

public class Foo { private String areaName; private String objectName; private String lineName; } 

Now I want to convert a List<Foo> to Map<String, Map<String, List<String>>>. I found this answer which helped me develop following code:

Map<String, Map<String, List<String>>> testMap = foos.stream().collect(Collectors.groupingBy(e -> e.getAreaName(), Collectors.groupingBy(e -> e.getObjectName(), Collectors.collectingAndThen(Collectors.toList(), e -> e.stream().map(f -> f.getLineName()))))); 

The only problem with this code is the part where it should convert to List<String>. I couldn't find a way to convert Foo to List in that part.

Another approach which results in Map<String, Map<String, List<Foo>>>:

Map<Object, Map<Object, List<Foo>>> testMap = ventures.stream().collect(Collectors.groupingBy(e -> e.getAreaName(), Collectors.groupingBy(e -> e.getObjectName(), Collectors.toList()))); 

What do I need to change in order to receive Map<String, Map<String, List<String>>> from List<Foo>?

1 Answer 1

13

In order to get a List of a different type than the type of the Stream elements, you should chain a Collectors.mapping collector to groupingBy:

Map<String, Map<String, List<String>>> testMap = foos.stream() .collect(Collectors.groupingBy(Foo::getAreaName, Collectors.groupingBy(Foo::getObjectName, Collectors.mapping(Foo::getLineName, Collectors.toList())))); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I can't believe i didn't see Collectors::mapping method!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.