Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 528
Churap Avatar asked Nov 11 '15 05:11

Churap


People also ask

Can we cast list to Map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

What is nested Map in Java?

Nested Map is used in many cases, such as storing students' names with their Ids of different courses. In this case, we create a Map having a key, i.e., course name and value, i.e., another Map having a key, i.e., Id and value, i.e., the student's name.

How do I access nested HashMap?

You can do it like you assumed. But your HashMap has to be templated: Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); Otherwise you have to do a cast to Map after you retrieve the second map from the first.


1 Answers

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)));
like image 119
Tagir Valeev Avatar answered Sep 17 '22 06:09

Tagir Valeev