Collectors.toMap does not compile

This code does not compile

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

Compilation error: the split (String) method is undefined for the Object type error in System.out.println (par .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?

ADDITIONAL INFORMATION

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

+6
source share
2 answers

Versions of IntelliJ do different (only red lines in the source editor in the IDE). The code must be compiled by the JDK successfully.

IntelliJ 13 is fine for your code. IntelliJ 12 weakly supports lambda expression. I also encountered similar problems between the two versions of IntelliJ when using a lambda expression.

0
source

I assume that you are using an IDE (e.g. Eclipse). For example, Eclipse uses its own compiler and does not use the javac command (from the JDK).

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

The problem is very simple: the Eclipse compiler cannot deduce the String type for the arguments to the collect method. Therefore, it simply displays Object (since this is a type that can be safely assumed). And Object does not know the split method.

You can make the compiler learn about String by explicitly 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 explicitly declaring the correct types of 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]))); 
+4
source

Source: https://habr.com/ru/post/978019/


All Articles