Collecting lists from an object list using Java 8 Stream API

后端 未结 2 1479
南旧
南旧 2020-12-30 01:36

I have a class like this

public class Example {
    private List ids;

    public getIds() {
        return this.ids; 
    }
}
相关标签:
2条回答
  • 2020-12-30 01:43

    Use flatMap:

    List<Integer> concat = examples.stream()
        .flatMap(e -> e.getIds().stream())
        .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-30 02:07

    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());
    
    0 讨论(0)
提交回复
热议问题