What do I need to do in order to make the following code type check? The problem is with s -> s[0]
, where s
is inferred to be a generic type T
instead of String[]
.
List<String[]> a = Arrays.asList("a.b","c.b")
.stream()
.map(s->s.split("\\."))
.collect(Collectors.toList());
Map<String,List<String>> b = a.stream()
.collect(Collectors.groupingBy(s -> s[0]));
The expected result should be a Map
like this:
{a: ["a.b"],
c: ["c.b"]}
The problem is with s -> s[0], where s is inferred to be a generic type T instead of String[].
Actually that's not the problem. s
is correctly inferred as a String[]
.
However,
a.stream().collect(Collectors.groupingBy(s -> s[0]));
produces a Map<String,List<String[]>>
, not a Map<String,List<String>>
. That's the problem.
If you want to join the String
s of the String
arrays into a single String
, you'll need an extra mapping step.
For example :
Map<String,List<String>> b =
a.stream()
.collect(Collectors.groupingBy(s -> s[0],
Collectors.mapping (s -> String.join (".", s),
Collectors.toList ())));
Output :
{a=[a.b], c=[c.b]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With