Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Lambda: concat list [duplicate]

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 ?

like image 233
Clem Avatar asked Jan 07 '15 10:01

Clem


People also ask

How to concatenate lists and sets in Java?

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.

How to concatenate streams in Java 8?

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.

How to concatenate multiple lists in guava?

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.

How to build a comma separated list of values in Java?

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.


1 Answers

That's what flatMap is for :

List<B> bList = aList.stream()
                     .flatMap(a -> a.bList.stream())
                     .collect(Collectors.toList());
like image 58
Eran Avatar answered Oct 02 '22 19:10

Eran