Shashank Agrawal
Shashank Agrawal

Reputation: 71

Java 8 Collectors.toMap with ArrayList as value

I want to convert given 2d array to map using java 8. Input - { { 1, 0 }, { 2, 0 }, { 3, 1 }, { 3, 2 } } The output should be of form Map<Integer, List> map = new HashMap<>(); Output - {1=[0], 2=[0], 3=[1, 2]}

Below is my solution

for (int[] prereq : prerequisites) {
            map.computeIfAbsent(prereq[0], k -> new ArrayList<>()).add(prereq[1]);
        }

Any better approach, if for loop can be replaced with streams.

Upvotes: 2

Views: 3629

Answers (2)

Eritrean
Eritrean

Reputation: 16498

Since your array rows always consist of a pair of numbers and you consider the first element as key and the second as value, it would be obvious at first glance if you map them to SimpleEntry:

int[][] prerequisites = { { 1, 0 }, { 2, 0 }, { 3, 1 }, { 3, 2 } };
    Map<Integer,List<Integer>> map = 
            Arrays.stream(prerequisites)
                  .map(arr -> new AbstractMap.SimpleEntry<>(arr[0], arr[1]))
                  .collect(Collectors.groupingBy(
                            Map.Entry::getKey,
                            Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

Upvotes: 3

Eklavya
Eklavya

Reputation: 18420

To collect into a Map that contains multiple values by key use Collectors.groupingBy.

int[][] prerequisites = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};
Map<Integer, List<Integer>> res = Arrays.stream(prerequisites).collect(
        Collectors.groupingBy(x -> x[0], Collectors.mapping(x -> x[1], Collectors.toList())));

Output:

{1=[0], 2=[0], 3=[1, 2]}

Upvotes: 7

Related Questions