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>
toStream<? extends Object>
How can I do that? (I need to do it with streams, it's all part of a bigger stream computation)
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.
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.
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.
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.
flatMap
expects mapping to stream, not to collection. Use
.stream().flatMap(x -> x.getTitles().stream())
// ^^^^^^^^ add this
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