Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 List<Foo> to Map<String, Map<String, List<String>>>

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>?

like image 371
XtremeBaumer Avatar asked Nov 01 '18 12:11

XtremeBaumer


1 Answers

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()))));
like image 110
Eran Avatar answered Sep 24 '22 04:09

Eran