Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 type check for Collectors.groupingBy

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"]}
like image 674
user3139545 Avatar asked Feb 06 '23 09:02

user3139545


1 Answers

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 Strings 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]}
like image 190
Eran Avatar answered Feb 18 '23 23:02

Eran