Skip to content

How can I collect two-dimensional Array into a Map<String, Set>?

I have an array of arrays of two strings.

var array = new String[][]{
    {"a", "1"},
    {"a", "2"},
    {"b", "3"},
    ...
};

How can I collect the above array into a Map<String, Set<String>> whose key is the first element of each array and the value is a set of second elements of the array?

So that I get following map?

// Map<String, Set<String>>
<"a", ["1, "2"]>,
<"b", ["3"]>,
...

So far, I found I can classify the first element of each array like this.

Arrays.stream(array).collect(Collectors.groupingBy(
        a -> ((String[])a)[0],
        // how can I collect the downstream?
);

Answer

You need a Collectors.mapping (also you don’t need to specify String[] inside)

var array = new String[][]{{"a", "1"}, {"a", "2"}, {"b", "3"},};

Map<String, Set<String>> res = Arrays.stream(array).collect(Collectors.groupingBy(
        a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toSet())
));

System.out.println(res); // {a=[1, 2], b=[3]}