Merging two Map with Java 8 Stream API

前端 未结 6 1135
孤城傲影
孤城傲影 2020-11-30 19:17

I have two (or more) Map objects. I\'d like to merge them with Java 8 Stream API in a way that values for common keys should be the maxim

6条回答
  •  囚心锁ツ
    2020-11-30 19:32

    I added my contribution to the proton pack library which contains utility methods for the Stream API. Here's how you could achieve what you want:

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

    Basically mergeKeys will collect the key-value pairs in a new map (providing a merge function is optional, you'll end up with a Map> otherwise) and recall stream() on the entrySet() to get a new MapStream. Then use collect() to get the resulting map.

提交回复
热议问题