Java 8 type checking for Collectors.groupingBy

What do I need to do to perform the following code type check? The problem is s -> s[0]where it sis defined as a generic type Tinstead 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 Mapas follows:

{a: ["a.b"],
 c: ["c.b"]}
+4
source share
1 answer

The problem is s → s [0], where s is inferred as the generic type T instead of String [].

Actually, this is not a problem. scorrectly displayed as String[]. Nonetheless,

a.stream().collect(Collectors.groupingBy(s -> s[0]));

creates a Map<String,List<String[]>>, not a Map<String,List<String>>. This is problem.

String String String, .

:

Map<String,List<String>> b = 
    a.stream()
     .collect(Collectors.groupingBy(s -> s[0],
                                    Collectors.mapping (s -> String.join (".", s), 
                                                        Collectors.toList ())));

:

{a=[a.b], c=[c.b]}
+8

Source: https://habr.com/ru/post/1665693/


All Articles