ThrowableException
ThrowableException

Reputation: 1426

Why same code works in Eclipse but doesn't even compile in IntelliJ

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

Answers (1)

howlger
howlger

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

Related Questions