Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 414
RVKS Avatar asked Jun 22 '15 20:06

RVKS


People also ask

What does the flatMap () function do?

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 ( arr.map(...args).flat() ), but slightly more efficient than calling those two methods separately.

How do you use flatMap in Stream?

We can use a flatMap() method on a stream with the mapper function List::stream. On executing the stream terminal operation, each element of flatMap() provides a separate stream. In the final phase, the flatMap() method transforms all the streams into a new stream.

What is difference between map () and flatMap () and reduce () method in Java Stream?

Both map and flatMap can be applied to a Stream<T> and they both return a Stream<R> . The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.

Can we convert string to Stream?

Conversion Using chars() The String API has a new method – chars() – with which we can obtain an instance of Stream from a String object. This simple API returns an instance of IntStream from the input String.


1 Answers

flatMap expects mapping to stream, not to collection. Use

.stream().flatMap(x -> x.getTitles().stream())
//                                   ^^^^^^^^ add this
like image 65
Pshemo Avatar answered Sep 28 '22 02:09

Pshemo