Reputation: 1426
Here are 2 code snippets, which are supposed to return the same result, as I used HashMap
in map factory
.
But the second code snippet doesn't compile in IntelliJ. Both codes work fine in Eclipse.
System.out.println
method required something where it can call toString
, but in IntelliJ I get this weird error, Why ?
Compileable code (both Eclipse & IntelliJ):
System.out.println(Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting())));
Erroneous Code (works in Eclipse but fails only in IntelliJ):
System.out.println(Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(
Function.identity(),
HashMap::new,
Collectors.counting())));
The error for second snippet in IntelliJ
Required type: String
Provided: Map
<java.lang.String,java.lang.Long> no instance(s) of type variable(s) K, V exist so that HashMap<K, V> conforms to String
Upvotes: 4
Views: 808
Reputation: 34255
That seems a bug of javac
which is used by IntelliJ IDEA. In contrast, Eclipse has its own compiler.
It fails with javac
of Java 8 and 11, but if the collector in collect(...)
is extracted to a var
variable (available since Java 10) than it compiles without errors with javac
of Java 11:
var collector = Collectors.groupingBy(Function.identity(),
HashMap::new,
Collectors.counting());
System.out.println(Arrays.stream(str.split(" ")).collect(collector));
Hence, the collector type can be inferred and used here.
As workaround for javac
, you can use the following code for Java 8 where var
is not available:
Collector<Object, ?, Map<Object, Long>> collector =
Collectors.groupingBy(Function.identity(),
HashMap::new,
Collectors.counting());
System.out.println(Arrays.stream(str.split(" ")).collect(collector));
Upvotes: 5