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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With