2014-11-05 20 views
8

Come si appiattisce unos (degli stessi tipi) dello stesso Map in Java 8?Flusso di mappe sulla mappa

Map<String, Long> toMap(Stream<Map<String, Long>> stream) { 
    return stream. ??? 
} 

risposta

14

mia sintassi può essere un po 'fuori, ma flatMap dovrebbe fare la maggior parte del lavoro per voi:

Map<String, Long> toMap(Stream<Map<String, Long>> stream) { 
    return stream.flatMap (map -> map.entrySet().stream()) // this would create a flattened 
                  // Stream of all the map entries 
       .collect(Collectors.toMap(e -> e.getKey(), 
              e -> e.getValue())); // this should collect 
                   // them to a single map 
} 
+0

La corrente() metodo non è definito per il tipo di mappa dmydlarz

+0

@DariuszMydlarz ho fissato il risposta. Utilizzare invece map.entrySet(). Stream(). – Eran

+5

È possibile utilizzare i riferimenti al metodo: 'Collectors.toMap (Map.Entry :: getKey, Map.Entry :: getValue)' (o se si importa la classe nidificata: 'Collectors.toMap (Entry :: getKey, Entry :: getValue)) – Holger

Problemi correlati