Seems like a very basic question, I want to convert my 2d string array into a Map
with List
as a Value.
I've tried something like below:
Map<String, List<String>> guestMap = Arrays
.stream(guests)
.collect(Collectors.groupingBy(e-> e[1], Collectors.toList()));
My nested array of strings like this
String[][] guests = {
{"A", "lizzard"},
{"B", "Gorilla"},
{"C", "lizzard"},
{"D", "Gorilla"},
{"E", "lizzard"},
{"F", "Gorilla"},
{"G", "lizzard"},
{"H", "Monkey"},
{"I", "lizzard"}
};
I know about a way of solving it using computeIfAbsent()
. But I'm looking for a solution purely using Stream API.
CodePudding user response:
Since elements in the stream are of type String[]
, with your current collector
Collectors.groupingBy(e-> e[1], Collectors.toList())
Map's Values would be of type List<String[]>
(whilst you need a List<String>
, not a list of arrays). Hence, you need to transform the stream elements received by the downstream Collector before storing them into a List.
As @Rogue has pointed out in the comment you need to use Collector mapping()
and the downstream of groupingBy()
. And toList()
should be in turn provided as the downstream Collector of mapping()
.
String[][] guests = {
{"A", "lizzard"},
{"B", "Gorilla"},
{"C", "lizzard"},
{"D", "Gorilla"},
{"E", "lizzard"},
{"F", "Gorilla"},
{"G", "lizzard"},
{"H", "Monkey"},
{"I", "lizzard"}
};
Map<String, List<String>> guestMap = Arrays.stream(guests)
.collect(Collectors.groupingBy(
e -> e[1],
Collectors.mapping(e -> e[0],
Collectors.toList())
));
guestMap.forEach((k, v) -> System.out.println(k " -> " v));
Output:
Monkey -> [H]
lizzard -> [A, C, E, G, I]
Gorilla -> [B, D, F]