You can achieve this using Collectors.groupingBy
by the first element of the array and use a mapping collector as a downstream to get the further values. Finally, the further downstream Collectors.toList
wraps the values. Use AbstractMap.SimpleEntry
for better manipulation with the array items.
Now, the solution only depends, whether each Integer[]
contains exactly 2 items or 2+ items:
Exactly 2 items in each array
Each Integer[]
always contain exactly two items (ex. new Integer[] {1, 23}
). Use Collectors.mapping
to get the array[1]
(entry's value) result into the List
.
Map<Integer, List<Integer>> map = list.stream()
.map(array -> new AbstractMap.SimpleEntry<>(array[0], array[1]))
.collect(Collectors.groupingBy(
AbstractMap.SimpleEntry::getKey,
Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList())));
Actually, the SimpleEntry
usage can be omitted and the whole stream simplified if you address the arrays directly:
Map<Integer, List<Integer>> map = list.stream()
.collect(Collectors.groupingBy(
array -> array[0],
Collectors.mapping(array -> array[1], Collectors.toList())));
2+ items in each array
Each Integer[]
can contain two or more items (ex. new Integer[] {1, 23, 24}
). Use Collectors.flatMapping
to get the array[1]
.. array[n]
items (entry's value) into the List
. Remember, you need to split the array first to perform the correct grouping, therefore the first element array[0]
is the key and array[1] .. array[n]
are values - that's why flatmapping is required.
Map<Integer, List<Integer>> map = list.stream()
.map(array -> new AbstractMap.SimpleEntry<>(
array[0],
Arrays.copyOfRange(array, 1, array.length)))
.collect(Collectors.groupingBy(
AbstractMap.SimpleEntry::getKey,
Collectors.flatMapping(
i -> Arrays.stream(i.getValue()),
Collectors.toList())));
Again, the whole stream can be simplified omitting the SimpleEntry
wrapper:
Map<Integer, List<Integer>> map = list.stream()
.collect(Collectors.groupingBy(
array -> array[0],
Collectors.flatMapping(
array -> Arrays.stream(Arrays.copyOfRange(array, 1, array.length)),
Collectors.toList())));
Consequently, thanks to geting a subarray which can result in an empty array, this solution also works when there is at least one element present in the Integer[]
array. A result with the array new Integer[] {3}
in the input would be:
{1=[23, 45], 2=[45, 54, 88], 3=[]}