2015-12-09 16 views
10

Ho una lista come questa:raggruppamento per Elenco dei Map in Java 8

List<Map<String, Long>> 

C'è un modo, utilizzando lambda, per convertire questo elenco per:

Map<String, List<Long>> 

Esempio:

Map<String, Long> m1 = new HashMap<>(); 
m1.put("A", 1); 
m1.put("B", 100); 

Map<String, Long> m2 = new HashMap<>(); 
m2.put("A", 10); 
m2.put("B", 20); 
m2.put("C", 100); 

List<Map<String, Long>> beforeFormatting = new ArrayList<>(); 
beforeFormatting.add(m1); 
beforeFormatting.add(m2); 

Dopo la formattazione:

Map<String, List<Long>> afterFormatting; 

che sarebbe simile:

A -> [1, 10] 
B -> [100, 20] 
C -> [100] 

risposta

10

È necessario flatMap il set di entrata di ogni mappa per creare un Stream<Map.Entry<String, Long>>. Quindi, questo Stream può essere raccolto con il collector groupingBy(classifier, downstream): il classificatore restituisce la chiave della voce e il collettore downstream associa la voce al suo valore e la raccoglie in un List.

Map<String, List<Long>> map = 
    list.stream() 
     .flatMap(m -> m.entrySet().stream()) 
     .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList()))); 

Questo codice ha bisogno delle seguenti importazioni statiche:

import static java.util.stream.Collectors.groupingBy; 
import static java.util.stream.Collectors.mapping; 
import static java.util.stream.Collectors.toList; 

Con il vostro esempio completo:

public static void main(String[] args) { 
    Map<String, Long> m1 = new HashMap<>(); 
    m1.put("A", 1l); 
    m1.put("B", 100l); 

    Map<String, Long> m2 = new HashMap<>(); 
    m2.put("A", 10l); 
    m2.put("B", 20l); 
    m2.put("C", 100l); 

    List<Map<String, Long>> beforeFormatting = new ArrayList<>(); 
    beforeFormatting.add(m1); 
    beforeFormatting.add(m2); 

    Map<String, List<Long>> afterFormatting = 
     beforeFormatting.stream() 
         .flatMap(m -> m.entrySet().stream()) 
         .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList()))); 

    System.out.println(afterFormatting); // prints {A=[1, 10], B=[100, 20], C=[100]} 
} 
+0

Grazie, Tunaki! :-) – test123

Problemi correlati