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.
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.
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.
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With