I want to count the different elements of a stream and am wondering why
Stream<String> stream = Stream.of("a", "b", "a", "c", "c", "a", "a", "d");
Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, 1, Integer::sum));
doesn't work. Eclipse tells me
The method toMap(Function, Function, BinaryOperator) in the type Collectors is not applicable for the arguments (( s) -> {}, int, Integer::sum)
By the way, I know about that solution:
Map<String, Long> counter2 = stream.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
So I have two questions:
- What is the mistake in my first approach?
- How would you implement such a counter?
EDIT: I solved the first question by myself:
Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
Java is expecting a function as second argument.