2015-11-11 16 views
6

ho Hava un elenco di classe A comeJava 8 lista alla mappa annidata

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

voglio trasferire aList a annidato Map mappata keyA e keyB

Così ho creato sotto il codice.

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;})); 

Ma questo codice non mi piace.

Penso che se io uso flatMap, posso codice migliore di questo.

Ma non so Come utilizzare flatMap per questo comportamento.

risposta

11

sembra che basta una cascata groupingBy:

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