I want to calculate different elements of a flow and I wonder 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));
does not work. Eclipse tells me
The toMap (Function, Function, BinaryOperator) method in the Collectors class is not applicable for arguments ((s) → {}, int, Integer :: sum)
By the way, I know about this solution:
Map<String, Long> counter2 = stream.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
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 myself:
Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
Java expects a function as a second argument.
java java-8 count java-stream collectors
principal-ideal-domain
source share