flatMap() to convert a stream of LinkedList<String> into a stream of String

4.2k views Asked by At

My goal is exactly what the title say. What I'm doing is:

.stream().flatMap(x -> x.getTitles())

getTitles() returns a LinkedList<String>, and I expected flatMap() to do the job and create a stream of Strings instead of a stream of LinkedList<String>, but Eclipse says:

Type mismatch: cannot convert from LinkedList<String> to Stream<? extends Object>

How can I do that? (I need to do it with streams, it's all part of a bigger stream computation)

1

There are 1 answers

5
Pshemo On BEST ANSWER

flatMap expects mapping to stream, not to collection. Use

.stream().flatMap(x -> x.getTitles().stream())
//                                   ^^^^^^^^ add this