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.