简体   繁体   中英

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?

Use flatMap :

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

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());

您可以使用 flatMap 替代 stream.map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM