简体   繁体   中英

Java 8 list to nested map

I hava a list of Class A like

class A {
 private Integer keyA;
 private Integer keyB;
 private String text;
}

I want to transfer aList to nested Map mapped by keyA and keyB

So I create below code.

Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
    .collect(Collectors.collectingAndThen(Collectors.groupingBy(A::getKeyA), result -> {
        Map<Integer, Map<Integer, List<A>>> nestedMap = new HashMap<Integer, Map<Integer, List<A>>>();
        result.entrySet().stream().forEach(e -> {nestedMap.put(e.getKey(), e.getValue().stream().collect(Collectors.groupingBy(A::getKeyB)));});
        return nestedMap;}));

But I don't like this code.

I think If I use flatMap , I can better code than this.

But I don't know How use flatMap for this behavior.

Seems that you just need a cascaded groupingBy :

Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
    .collect(Collectors.groupingBy(A::getKeyA, 
                 Collectors.groupingBy(A::getKeyB)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM