I am trying to count the integer numbers in an array using Collectors.groupingBy from the Java 8 API, but I am getting some strange compilation errors.
Here is my code:
List<Integer> l = Arrays.asList(1, 1, 1, 2, 3, 3, 3, 3); Map<Integer, Integer> x = l.stream().collect(groupingBy(i -> i, counting()));
Unfortunately, this does not compile, resulting in the following error:
error: incompatible types: inferred type does not conform to equality constraint(s) Map<Integer, Integer> x = l.stream().collect(groupingBy(i -> i, counting())); ^ inferred: Integer equality constraints(s): Integer,Long 1 error
This seems to be a problem with the generic type, because when I delete the generic map type, it compiles. Here is another test:
List<Integer> l = Arrays.asList(1, 1, 1, 2, 3, 3, 3, 3); Map x = l.stream().collect(groupingBy(i -> i, counting())); System.out.println(x);
And the result will be correct as expected:
{1=3, 2=1, 3=4}
Any ideas on how to solve this without having to drop all types here and there?