0

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()?

  • 4
    Raw types went out of fashion a decade ago. Add some type parameters. – Joe C Sep 30 '17 at 17:33
  • 2
    [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321) – Pshemo Sep 30 '17 at 17:34
  • 1
    What is `list::toString` supposed to do? – Andy Turner Sep 30 '17 at 17:35
  • Sorry i just edited my question, it was supposed to be list1::toString not list::toString and List list1 not List list1 –  Sep 30 '17 at 17:43
  • 1
    Do you understand the difference between a *class* and an *object*? `list1` is an object and `list1::toString` is equivalent to `() -> list1.toString()`. – Holger Oct 01 '17 at 08:23

1 Answers1

3

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()));  
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • @Mureinik i just edited my question. But toString() is a method in each element in list1 since it's inherited from Object by default, no ? –  Sep 30 '17 at 17:47
  • 1
    @Neokyuubi `list1` isn't an element of the stream. You could use the `Object::toString` or `String::toString` method reference, although calling `toString()` on a `String` isn't very useful. – Mureinik Sep 30 '17 at 17:50