Collecting lists from an object list using Java 8 Stream API

Jakob Abfalter :

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?

Andy Turner :

Use flatMap:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430359&siteId=1