If you have a List<Map<String, String>> that represents a list of maps to merge, you can have
Map<String, String> result = maps.stream() .flatMap(m -> m.entrySet().stream()) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.mapping( Map.Entry::getValue, Collectors.collectingAndThen(Collectors.<String>toSet(), s -> String.join("", s)) ) ));
This flat map maps each map to its stream of records. Then Stream is grouped by the value of each record, and all individual elements with the same key are compared with their value, combined.
The distinctive part becomes possible by first collecting all the values ββinside a Set .
Code example:
public static void main(String[] args) { List<Map<String, String>> maps = new ArrayList<>(); maps.add(new HashMap<String, String>(){{ put("Name", "XXX"); put("Phn", "123"); put("Work", ""); }}); maps.add(new HashMap<String, String>(){{ put("Name", "XXX"); put("Phn", "456"); put("Work", "xyz"); }}); maps.add(new HashMap<String, String>(){{ put("Name", "XXX"); put("Phn", "789"); put("Work", ""); }}); Map<String, String> result = maps.stream() .flatMap(m -> m.entrySet().stream()) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.mapping( Map.Entry::getValue, Collectors.collectingAndThen(Collectors.<String>toSet(), s -> String.join("", s)) ) )); System.out.println(result);
Tunaki
source share