Java Stream: the collection in the list of all non-zero collections received on the map ()

I have an idList collection that contains row ids. The getCollection function returns a collection of elements (type MyType) for a single ID . In addition, it can return null.

So, for many identifiers from idList, I would get some null values ​​and some collections.

The goal is to collect all getCollection responses for a set of identifiers into a final list.

I imagined something like

List<MyType> reply = idList.stream().map(id -> getCollection(id)) .filter(p -> p != null).collect(Collectors.toList()); 

but this does not seem to be a valid expression. How to do it?

Also, how about doing this implementation?

+5
source share
1 answer

You need to use flatMap -

 List<MyType> reply = idList.stream() .map(id -> getCollection(id)) .filter(collection -> collection != null) .flatMap(Collection::stream) .collect(Collectors.toList()); 

If you are thinking about the differences between map and flatMap , you can consult this excellent answer -

Both maps and flatMap can be applied to the Stream, and they both return the stream. The difference is that the map operation produces one output value for each input value, while the flatMap operation produces an arbitrary number (zero or more) of values ​​for each input value.

This is reflected in the arguments of each operation.

The card operation takes a function that is called for each value in the input stream and produces a single result value, which is sent to the output stream.

The flatMap operation accepts a function that conceptually wants to consume a single value and produce an arbitrary number of values. However, in Java, it is cumbersome for a method to return an arbitrary number of values, since methods can only return zero or one value. One could imagine an API where the mapper function for flatMap takes a value and returns an array or list of values, which are then sent to the output. Given that this is a stream library, a particularly suitable way to represent an arbitrary number of return values ​​for the converter is that the function itself returns a stream! The values ​​from the stream returned by the cartographer are merged from the stream and the output stream is transmitted. The “clumps” of values ​​returned by each call to the mapper function do not differ at all in the output stream, thus saying that the output was “flattened”.

The mapper function is usually used for flatMap Stream.empty () if it wants to send null values ​​or something like Stream.of (a, b, c) if it wants to return multiple values. But of course, any thread can be returned.

+4
source

Source: https://habr.com/ru/post/1265247/


All Articles