java下map合併

java8下map合併可以有以下幾種方式:

map爲待合併集合,map2爲被合併集合(將map2中元素合併到map中)

  1. map.merge()
    map2.forEach((key, value) -> {
          map.merge(key, value, (origin, newVlue) -> {
            origin.putAll(newVlue);
            return origin;
          });
        });

     

  2. Stream.concat()
    Stream
            .concat(map.entrySet().stream(), map2.entrySet().stream())
            .collect(Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue,
                (origin, newValue) -> {
                  origin.putAll(newValue);
                  return origin;
                }));

     

  3. Stream.of()
    Stream
            .of(map, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue,
                (origin, newValue) -> {
                  origin.putAll(newValue);
                  return origin;
                }));

     

  4. Simple Streaming
    map2.entrySet()
            .stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (origin, newValue) -> {
                  origin.putAll(newValue);
                  return origin;
                }, () -> map // 彙總者
            ));

     

參考:https://www.baeldung.com/java-merge-maps

源碼:https://github.com/eugenp/tutorials/tree/master/java-collections-maps-2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章