2014-04-13 24 views
46

Mam dwa (lub więcej) obiektów Map<String, Integer>. Chciałbym połączyć je z API Java 8 Stream w taki sposób, aby wartości dla wspólnych kluczy były maksymalnymi wartościami.Scalanie dwóch Map <String, Integer> z 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); 
} 

Jak mogę uczynić tę metodę testu zieloną?

Grałem z collect i Collectors przez jakiś czas bez powodzenia.

(ImmutableMap i newArrayList są od Google guawy.)

Odpowiedz

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

Świetnie! Potrzebuję tylko jednej rzeczy, zamiast maksimum potrzebuję średniej. Jak mogę to zrobić? –

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

Obejmuje ogólnym przypadku dla każdej listy rozmiarów i powinien pracować z wszelkiego rodzaju, po prostu zamienić się z Integer::max i/lub HashMap::new zgodnie z potrzebami.

Jeśli nie obchodzi, których wartość wychodzi w seryjnej, jest znacznie czystsze rozwiązanie:

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

I jako metody rodzajowe:

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

dodałam mój wkład do proton pack library który zawiera metody użytkowe dla Stream API. Oto w jaki sposób można osiągnąć to, co chcesz:

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

Zasadniczo mergeKeys będą zbierać par klucz-wartość w nowej mapie (o ile funkcja scalania jest opcjonalne, można skończyć z Map<String, List<Integer>> inaczej) oraz przypomnieć stream() na entrySet(), aby uzyskać nowy MapStream. Następnie użyj collect(), aby uzyskać wynikową mapę.

1

Korzystanie StreamEx można zrobić:

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

To ponad inżynierii, można to zrobić tylko:

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

Nie gwarantuje to tego warunku: "wartości wspólnych kluczy powinny być maksymalna wartość ". – palacsint

+1

To nawet nie próbuje _adress_ tego warunku. –

1

Utworzyłem wizualną reprezentację, co @srborlongan zrobił, dla każdego, kto może być zainteresowany.

enter image description here