简体   繁体   中英

How can put multiple Hashmap in java into a new hashmap?

I have eight HashMaps in Java as follows:

     HashMap<String, Double> map1= new HashMap<String, Double>();
        HashMap<String, Double> map2= new HashMap<String, Double>();
        HashMap<String, Double> map3= new HashMap<String, Double>();
        HashMap<String, Double> map4= new HashMap<String, Double>();
        HashMap<String, Double> map5= new HashMap<String, Double>();
        HashMap<String, Double> map6= new HashMap<String, Double>();
        HashMap<String, Double> map7= new HashMap<String, Double>();
        HashMap<String, Double> map8= new HashMap<String, Double>();

I want to merge all in a new HashMap lets say NEW_MAP. How can I do this?

I am not sure if I am following your question correctly,there is a putAll() method in Map interface, you can merge them all to new HashMap by this method

eg :

Map<K,V> nhm = new HashMap<>();

nhm.putAll(map1);
...........
...........
nhm.putAll(map8);

Then decide what to do with duplicate keys and use the third parameter of Collectors#tomap: (Collectors.toMap(keyMapper, valueMapper, mergeFunction))

Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
      .flatMap(m -> m.entrySet().stream()) 
      .collect(Collectors.toMap(
                Entry::getKey, Entry::getValue, (oldValue, newValue) -> newValue
              )
      );

The above for example will keep the last seen value if duplicates are ditected. You can change it to whatever you want according to your requirements:

keep the first value seen: (oldValue, newValue) -> oldValue

merge the two, eg by adding them: (oldValue, newValue) -> old + new

merge the two, eg by multiplying them: (oldValue, newValue) -> old * new

remove value: (oldValue, newValue) -> null

....

You can combine usage of putAll from RIPAN and Stream.of from Eritrean for simple putAll:

HashMap<String, Double> NEW_MAP= new HashMap<String, Double>();
Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
.forEach(NEW_MAP::putAll);

But if you want some custom logic during merging duplicate keys, you can do as below (with choosing min value for example):

HashMap<String, Double> NEW_MAP= new HashMap<String, Double>();
Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
        .flatMap(m -> m.entrySet().stream())
        .forEach(e -> NEW_MAP.merge(e.getKey(), e.getValue(),
                (v1, v2) -> Math.min(v1, v2)
        ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM