Search code examples
javahashmapmultimap

How to merge two ArrayList<Map<String, String>> to one?


ArrayList<Map<String, String>> result1

result1 is like

(1, a)
(2, a)
(3, b)
(4, e)
(5, e)

ArrayList<Map<String, String>> result2

result2 is like

(1,android)
(2,ios)
(3,android)
(4,android)
(5,ios)

I want to merge the two maps to build a map like this one

(1, ( a, android))
(2, ( a, ios))
(3, ( b, android))
(4, (e, android))
(5, (e, ios))

How to make this happen?


Solution

  • You can merge two streams with Stream.concat() and group them with Collectors.groupingBy() and Collectors.mapping():

    Map<String, String> first = Map.of("1", "a", "2", "a");
    Map<String, String> second = Map.of("1", "android", "2", "ios");
    Map<String, List<String>> result = Stream.concat(first.entrySet().stream(), second.entrySet().stream())
                .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));
    System.out.println(result);
    

    will output:

    {1=[a, android], 2=[a, ios]}