我想计算流的不同元素,并想知道为什么
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));
无效。 Eclipse告诉我
类型为Collectors的toMap(Function,Function,BinaryOperator)方法不适用于参数((s)-> {},int,Integer :: sum)
顺便说一下,我知道该解决方案:
Map<String, Long> counter2 = stream.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
所以我有两个问题:
编辑:我自己解决了第一个问题:
Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
Java期望函数作为第二个参数。
确实有几种方法可以做到。您没有提到的是.collect(groupingBy(x -> x, summingInt(x -> 1)));
如果您不使用并行流,则以下内容应该起作用: