Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collectors.toMap doesn't compile

This code doesn't compile

List<String> pairs = new ArrayList<>();
System.out.println(pairs.stream().collect(Collectors.toMap(x -> x.split("=")[0], x -> x.split("=")[1])));

Compilation error is: The method split(String) is undefined for the type Object error at System.out.println(pairs.stream().collect(Collectors.toMap(x -> x.split("=")[0], x -> x.split("=")[1])));

But this one compiles fine

List<String> pairs = new ArrayList<>();
Map<String,String> map = pairs.stream().collect(Collectors.toMap(x -> x.split("=")[0], x -> x.split("=")[1]));
System.out.println(map);

Can someone explain why?

MORE INFORMATION

It was intellij 12; jdk1.8.0_11; windows 64

like image 290
Eugene To Avatar asked Nov 11 '14 09:11

Eugene To


2 Answers

I assume you are using an IDE (like Eclipse). Eclipse - for example - uses its own compiler and does not utilize the "javac" command (from JDK).

So, I can reproduce your problem, but only with Eclipse. Simply compiling this code on command line with "javac" works just fine.

The problem is very simple: The Eclipse compiler is not able to infer the type String for the collect method's arguments. So it simply infers Object (as this is the type, the compiler can safely assume). And an Object does not know the split method.

You can force the compiler to know about String by explicitely declaring the type inside the lambda:

List<String> pairs = new ArrayList<>();
System.out.println(pairs.stream().collect(Collectors.toMap((String x) -> x.split("=")[0], x -> x.split("=")[1])));

... or by explicitely declaring the correct types for the geneirc toMap method:

List<String> pairs = new ArrayList<>();
System.out.println(pairs.stream().collect(Collectors.<String, String, String> toMap(x -> x.split("=")[0], x -> x.split("=")[1])));
like image 192
Seelenvirtuose Avatar answered Nov 20 '22 20:11

Seelenvirtuose


Versions of IntelliJ make different(Just red lines in source editor in IDE). The code should be compiled by JDK successfully.

IntelliJ 13 is OK for your code. IntelliJ 12 supports lambda expression poorly. I also met similar problems between two versions of IntelliJ when using lambda expression.

like image 1
卢声远 Shengyuan Lu Avatar answered Nov 20 '22 19:11

卢声远 Shengyuan Lu