Combining similar hashmaps in java

HashMap<String, String> hashMap1:

       name : ranjith
       city : san jose

HashMap<String, String> hashMap2:

       name : sandeep
       city : san jose

HashMap<String, String> hashMap3:

       name : rohith
       city : san jose

I want to convert the above hashmaps to HashMap<String, List<String>> hashMap4:

      name : [ranjith, sandeep, rohith]
      city : [san jose]

To make this merge, is there any direct path, or should I go through Iterating over each element, find the similarities and then merge

+4
source share
1 answer

This will be compiled into Map<String, Set<String>>, which seems more appropriate than a list, as you collect unique values. It uses static import java.util.stream.Collectors.*.

Map<String, Set<String>> hashMap4 = Stream.of(hashMap1, hashMap2, hashMap3)
        .map(Map::entrySet)
        .flatMap(Set::stream)
        .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())));

Here is the version of Java 7. Not so clean and concise, but still not too complicated.

Map<String, Set<String>> hashMap4 = new HashMap<>();
for (Map<String, String> map : Arrays.asList(hashMap1, hashMap2, hashMap3)) {
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String key = entry.getKey();
        Set<String> values = hashMap4.get(key);
        if (values == null) {
            hashMap4.put(key, values = new HashSet<>());
        }
        values.add(entry.getValue());
    }
}
+4
source

Source: https://habr.com/ru/post/1650245/


All Articles