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());
}
}
source
share