Converting Nested For Loops To Streams

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-19 07:45:26

问题


I'm having some trouble understanding streams. I've looked around and can't seem to find an example that matches my use case.

I have an existing nested for loop:

List<ObjectB> objectBs = new ArrayList<ObjectB>();
for (ObjectA objA: objectAList) {
    for (ObjectB objB: objA.getObjectBList()) {
        if (objB.getNumber() != 2) {
            objectBs.add(objB);
        }
    }
}

Alot of exampls show how to add objB.getNumber() to a list but not objB.


回答1:


You can use flatMap to obtain a Stream<ObjectB> of all the ObjectB instances and filter the ObjectB's of the required number :

List<ObjectB> objectBs = 
    objectAList.stream()
               .flatMap (a -> a.getObjectBList().stream())
               .filter (b -> b.getNumber() != 2)
               .collect (Collectors.toList());


来源:https://stackoverflow.com/questions/36744975/converting-nested-for-loops-to-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!