2014-04-13 17 views
46

Ho due (o più) oggetti Map<String, Integer>. Mi piacerebbe unirli con l'API Java 8 Stream in modo che i valori per le chiavi comuni siano il massimo dei valori.Unione di due mappe <String, Integer> con Java 8 Stream API

@Test 
public void test14() throws Exception { 
    Map<String, Integer> m1 = ImmutableMap.of("a", 2, "b", 3); 
    Map<String, Integer> m2 = ImmutableMap.of("a", 3, "c", 4); 
    List<Map<String, Integer>> list = newArrayList(m1, m2); 

    Map<String, Integer> mx = list.stream()... // TODO 

    Map<String, Integer> expected = ImmutableMap.of("a", 3, "b", 3, "c", 4); 
    assertEquals(expected, mx); 
} 

Come posso rendere questo metodo di prova verde?

Ho giocato con collect e Collectors per un po 'senza alcun successo.

(ImmutableMap e newArrayList sono da Google Guava.)

risposta

68
@Test 
public void test14() throws Exception { 
    Map<String, Integer> m1 = ImmutableMap.of("a", 2, "b", 3); 
    Map<String, Integer> m2 = ImmutableMap.of("a", 3, "c", 4); 

    Map<String, Integer> mx = Stream.of(m1, m2) 
     .map(Map::entrySet)   // converts each map into an entry set 
     .flatMap(Collection::stream) // converts each set into an entry stream, then 
            // "concatenates" it in place of the original set 
     .collect(
      Collectors.toMap(  // collects into a map 
       Map.Entry::getKey, // where each entry is based 
       Map.Entry::getValue, // on the entries in the stream 
       Integer::max   // such that if a value already exist for 
            // a given key, the max of the old 
            // and new value is taken 
      ) 
     ) 
    ; 

    /* Use the following if you want to create the map with parallel streams 
    Map<String, Integer> mx = Stream.of(m1, m2) 
     .parallel() 
     .map(Map::entrySet)   // converts each map into an entry set 
     .flatMap(Collection::stream) // converts each set into an entry stream, then 
            // "concatenates" it in place of the original set 
     .collect(
      Collectors.toConcurrentMap(  // collects into a map 
       Map.Entry::getKey, // where each entry is based 
       Map.Entry::getValue, // on the entries in the stream 
       Integer::max   // such that if a value already exist for 
            // a given key, the max of the old 
            // and new value is taken 
      ) 
     ) 
    ; 
    */ 

    Map<String, Integer> expected = ImmutableMap.of("a", 3, "b", 3, "c", 4); 
    assertEquals(expected, mx); 
} 
+0

Grande! Ho solo bisogno di una cosa diversa, invece di max, ho bisogno di media. Come posso farlo? –

+1

@FirasAlMannaa https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#average-- –

48
Map<String, Integer> mx = new HashMap<>(m1); 
m2.forEach((k, v) -> mx.merge(k, v, Integer::max)); 
12
mx = list.stream().collect(HashMap::new, 
     (a, b) -> b.forEach((k, v) -> a.merge(k, v, Integer::max)), 
     Map::putAll); 

Questo copre il caso generale per qualsiasi elenco dimensioni e dovrebbe funzionare con qualsiasi tipo, basta scambiare la Integer::max e/oppure HashMap::new come desiderato.

Se non vi interessa quale valore viene fuori in un'unione, c'è una soluzione molto più pulito:

mx = list.stream().collect(HashMap::new, Map::putAll, Map::putAll); 

E come metodi generici:

public static <K, V> Map<K, V> mergeMaps(Stream<? extends Map<K, V>> stream) { 
    return stream.collect(HashMap::new, Map::putAll, Map::putAll); 
} 

public static <K, V, M extends Map<K, V>> M mergeMaps(Stream<? extends Map<K, V>> stream, 
     BinaryOperator<V> mergeFunction, Supplier<M> mapSupplier) { 
    return stream.collect(mapSupplier, 
      (a, b) -> b.forEach((k, v) -> a.merge(k, v, mergeFunction)), 
      Map::putAll); 
} 
1

ho aggiunto il mio contributo alla proton pack library che contiene metodi di utilità per l'API Stream. Ecco come si potrebbe ottenere ciò che si vuole:

Map<String, Integer> mx = MapStream.ofMaps(m1, m2).mergeKeys(Integer::max).collect(); 

Fondamentalmente mergeKeys raccoglierà le coppie chiave-valore in una nuova mappa (fornendo un funzione di unione è opzionale, vi ritroverete con un Map<String, List<Integer>> altro) e richiamano stream() su entrySet() per ottenere un nuovo MapStream. Quindi utilizzare collect() per ottenere la mappa risultante.

1

Usando StreamEx si può fare:

StreamEx.of(m1, m2) 
    .flatMapToEntry(x -> x) 
    .grouping(IntCollector.max()) 
-3

Questo è finita di ingegneria, si può fare proprio:

map3 = new HashMap<>(); 
map3.putAll(map1); 
map3.putAll(map2); 
+5

Ciò non garantisce questa condizione: "i valori per le chiavi comuni devono essere il massimo dei valori ". – palacsint

+1

Non tenta nemmeno di _adressare questa condizione. –

1

Ho creato una rappresentazione visiva di ciò che ha fatto @srborlongan, per tutti coloro che potrebbe essere interessato

enter image description here