[Solved] Array to Map: no suitable method found for Collectors.toMap [closed]


Actually the 1 is the error. The value 1 cannot serve as the valueMapper, whose type should be Function<? super T, ? extends U>.

In your example the value mapper should be a function that accepts an element of your Stream (a String) and returns an Integer. The lambda expression s -> 1 will do.

The following works:

String[] arr = {"two", "times", "two", "is", "four"};
Map<String,Integer> map = Arrays.stream(arr).collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
System.out.println (map);

Output:

{times=1, four=1, is=1, two=2}

1

solved Array to Map: no suitable method found for Collectors.toMap [closed]