Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse cannot infer correct type from java 8 stream

The following code works fine in all online java compilers but eclipse throws compiler error. Is it a bug in eclipse or am I missing some setting somewhere? A simple fix to silence eclipse? online: https://ideone.com/l0bbhz. Note: This is a simplified cooked-up example to just point to the problem. I understand flatMap is not necessary in this case. In the actual case, I really need flatMap

package dummy;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class LearnJava {

    public static void main(String[] args) {
        String[] sa = {"ne", "two", "three"};
        List<String> l = Arrays.stream(sa)
                .flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))
                .collect(toList());
        System.out.println(l.get(0));
    }

}

Error in eclipse console.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert from List<Object> to List<String>

    at dummy.LearnJava.main(LearnJava.java:13)

My eclipse version:

Eclipse Java EE IDE for Web Developers.

Version: Luna Service Release 2 (4.4.2) Build id: 20150219-0600


Update: I went with this minor workaround. It works without major refactoring!

.flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))

To

.<String>flatMap(s -> Collections.singleton(s).stream().map(c -> c.toUpperCase()))
like image 925
balki Avatar asked Jun 09 '16 21:06

balki


1 Answers

The Eclipse compiler is not perfect. Sometimes you'll hit issues such as this. For example, there are currently two bugs open related to flatMap and type interference - 482664 and 502158.

If you believe the code is legit, which is strongly the case when javac compiles it without issues, then you should open a bug and post a snippet there in order to let them know about it. This helps improving the compiler.

like image 168
Gunnar Avatar answered Oct 05 '22 18:10

Gunnar