I am aware my question is very similar to Count int occurrences with Java8 , but I still cannot solve my case, which must be easier to solve.
The need is to count how many times integers repeat in a stream of integers (will be coming from a file, may be up to 1000000 integers). I thought it might be useful to create a map, where Integer will be a Key, and number of occurrences will be a value.
The exception is
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)
However, in Java 8 there is a Collectors.groupingBy
, which should suffice
Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,Collector<? super T, A, D> downstream)
The problem is that my code is not compiling and I do not see - why. I simplified it to this:
Map<Integer,Integer> result = IntStream.range(0,100).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
What is the reason for not compiling? Thank you in advance :)