-6

I want to convert array into Map using Java 8 streams:

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

The s -> s part is marked as error

no instance(s) of type variable(s) T, U exists so that Integer conforms to Function

1 Answers1

2

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}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Not sure why this is downvoted, as it's correct. Though `Collectors.counting()` would probably be the better alternative – Lino Feb 13 '20 at 12:07