我知道我的问题与 Count int occurrences with Java8 非常相似 , 但我仍然无法解决我的案子,这一定更容易解决。
需要计算整数流中整数重复的次数(将来自文件,可能多达 1000000 个整数)。我认为创建一个映射可能会有用,其中整数将是一个键,出现次数将是一个值。
异常(exception)是
Error:(61, 66) java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer found: java.util.stream.Collector> reason: cannot infer type-variable(s) R (actual and formal argument lists differ in length)
但是,在 Java 8 中有一个 Collectors.groupingBy
,这应该足够了
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream)
问题是我的代码没有编译,我不明白 - 为什么。 我将其简化为:
Map<Integer,Integer> result = IntStream.range(0,100).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
编译不通过的原因是什么? 提前谢谢你:)
最佳答案
IntStream 有一个方法 collect
其中第二个参数对 int
进行操作不是对象。使用 boxed()
变成一个IntStream
进入Stream<Integer>
还有 counting()
返回 long
.
Map<Integer, Long> result = IntStream.range(0, 100).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
关于java - 使用 Java 8 创建 int 事件映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31877727/