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

I have a list of lines:

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

Then convert everything to a list like: "a1","a2","b1","b2" wrote the following:

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

But I had an error: "Type of mismatch: cannot be converted from List<Serializable> to List<String> ". I handled a problem changing to this:

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

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

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

And again, Stream.of() internally uses (and returns the result) Arrays.stream() . So, again, what is wrong in the first case?

+8
java arrays eclipse java-8 java-stream
source share
1 answer

This is an Eclipse error.

Error 508834 , thanks @Tunaki


Pay attention to 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[]> ? those. what type of varags; are you passing your array the first parameter (so varargs are an array of arrays) or are you passing your array like all parameters?

It's your problem.

+6
source share

All Articles