I am trying to concat list of a stream and process it.
class A {
public List<B> bList;
}
List<A> aList;
aList.stream().map(a -> a.bList)....
Here i get several list of b.
But, I would like to collect all my b in only one list. Any ideas ?
To concatenate Lists, Sets and Arrays we will convert them into stream first and using concat () we will combine them. The output stream can be converted into List, Set etc using methods of Collectors such as toList (), toSet () etc.
On this page we will provide Java 8 concat Streams, Lists, Sets, Arrays example. Stream provides concat () method to concatenate two streams and will return a stream.
The stream has a concat () method that takes two streams as input and creates a lazily concatenated stream out of them. We can use it to concatenate multiple lists, as shown below: 4. Using Guava’s Iterables Class Guava’s Iterables class provides many static utility methods that operate on or return objects of type Iterable.
Imagine a simple situation where we want to build a comma separated list of values from a list like the one here: Let's do it a bit differently and replace the comma symbol with a semicolon. What we did until Java 8 was iterate over the list and append using the well-known Java class StringBuilder, or StringBuffer based on the use case.
That's what flatMap is for :
List<B> bList = aList.stream()
.flatMap(a -> a.bList.stream())
.collect(Collectors.toList());
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