Jakob Nielsen
Jakob Nielsen

Reputation: 5198

Collecting lists from an object list using Java 8 Stream API

I have a class like this

public class Example {
    private List<Integer> ids;

    public getIds() {
        return this.ids; 
    }
}

If I have a list of objects of this class like this

List<Example> examples;

How would I be able to map the id lists of all examples into one list? I tried like this:

List<Integer> concat = examples.stream().map(Example::getIds).collect(Collectors.toList());

but getting an error with Collectors.toList()

What would be the correct way to achive this with Java 8 stream api?

Upvotes: 33

Views: 73401

Answers (3)

Here is an example of how to use Stream and Map to collect the object list:

List<Integer> integerList = productsList.stream().map(x -> x.getId()).collect(Collectors.toList());

Upvotes: 2

holi-java
holi-java

Reputation: 30686

Another solution by using method reference expression instead of lambda expression:

List<Integer> concat = examples.stream()
                               .map(Example::getIds)
                               .flatMap(List::stream)
                               .collect(Collectors.toList());

Upvotes: 10

Andy Turner
Andy Turner

Reputation: 140318

Use flatMap:

List<Integer> concat = examples.stream()
    .flatMap(e -> e.getIds().stream())
    .collect(Collectors.toList());

Upvotes: 58

Related Questions