Reputation: 71
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
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
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