Java 8 - Type mismatch: cannot convert from List<Serializable> to List<String>

freedev :

I have a list of Strings:

List<String> list = Arrays.asList("a1,a2", "b1,b2");

Then to convert everything in a list like: "a1","a2","b1","b2" wrote this:

List<String> ss1 = list.stream()
                       .flatMap(s -> Stream.of(s.split(",")))
                       .collect(Collectors.toList());

But I had an error: "Type mismatch: cannot convert from List<Serializable> to List<String>". I handled the problem changing into this:

List<String> ss2 = list.stream()
                       .flatMap(s -> Arrays.stream(s.split(",")))
                       .collect(Collectors.toList());

Eclipse Neon suggests that the difference is in the flatMap return type. First flatMap returns a List<Serializable> second returns a List<String>.

But both Stream.of() and Arrays.stream() returns a <T> Stream<T> (Eclipse suggests that they both returns a Stream<String>).

And again, Stream.of() internally use (and returns the output of) Arrays.stream(). So, again, what's wrong in the first case?

Boris the Spider :

This is an Eclipse bug

Bug 508834, thanks to @Tunaki


Notice the method signatures:

//Stream.of
<T> Stream<T> of(T... values)
//Arrays.stream
<T> Stream<T> stream(T[] array)

Now, for Arrays.stream it is obvious that a call with an array of type T will return a Stream<T>. But with Stream.of should it return Stream<T> or Stream<T[]>? i.e. what is the type of the varags; are you passing your array are the first parameter (so the varargs are an array of arrays) or are you passing your array as all the parameters?

That's your issue.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=456870&siteId=1