简体   繁体   中英

No suitable method found for groupingBy for List<String, Integer>

Giving this code :

List<String> list1 = Arrays.asList("Collect","Collection","by","Collectors");  
Map<String, Long> map = list1.stream().collect(Collectors.groupingBy(list1::toString, Collectors.counting()));  
System.out.println(map);  

It shows me :

error: no suitable method found for groupingBy(list::toString,Collector< Object,CAP#1,Long>)

I know that if list1 was a custom class that have let's say getName method and replace list1::toString by list1::getName it would work, but why not toString()?

The key of gorupingBy should be a method each element of the stream has. Since every element is a String , not a List , List::toString can't be used. Instead, you should apply toString to the element. Or since the elements are already strings, just call Function.indentity :

Map<String, Long> map = 
   list1.stream()
        .collect(Collectors.groupingBy
                            (Function.identity(), Collectors.counting()));  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM