首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用于检查和返回特定对象的java流操作

用于检查和返回特定对象的java流操作
EN

Stack Overflow用户
提问于 2018-10-22 01:46:51
回答 1查看 214关注 0票数 1

我正在尝试学习Java Stream API,并且正在编写一些示例。

所以我的例子如下:

我有一个列表列表,每个列表可以包含许多节点。

我想要一个程序,它检查并返回一个满足某些条件的节点。

代码语言:javascript
复制
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
        public static void main( String[] args ) {
        ArrayList<ArrayList<Node>> lists =  new ArrayList<>();
        /*here i'm creating a list of 10 list from 0 to 9
        * and each list will have one node, the nodes will have a random 
        degree
        */
        IntStream.range(0,10).forEach(  index -> {
                                                lists.add(new ArrayList<>());
                                                int random=new Random().nextInt(10) + 1;
                                                lists.get(index).add(new Node(random));
        });

        Node specificLsit = getaSpecificNode(lists);
    }

   /*we chould retun a new Node(1) if there is a node that have a degree=1
    *and a new Node(2) id there is a node with degree= 2 
    *or null if the above condition fails.
    *so what is the java stream operation to writre for that purpose.
    */
    private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
        Node nodeToReturn =null;
        //code go here to return the desired result
        return nodeToReturn;
    }
}

class Node{
    int degree;

    Node(int degree){
        this.degree = degree;
    }
    @Override
    public String toString() {
        return this.degree+"";
    }
}

2 for循环很容易解决这个问题,但我想要一个使用stream api的解决方案。

我尝试过的:

代码语言:javascript
复制
 private static Node getaSpecificNode( ArrayList<ArrayList<Node>> lists ) {
    Node nodeToReturn =null;
    lists.forEach((list)->{
        list.forEach((node)->{
            if (node.degree ==1 || node.degree ==2 )
                nodeToReturn = node;

        });

    });
    return nodeToReturn ;
}

不幸的是,我得到了一个编译错误,变量nodeToReturn应该是最终的,但在我的例子中,我正在尝试修改它。

有没有更好的解决方案?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-22 02:00:57

这应该能起到作用:

代码语言:javascript
复制
lists.stream().flatMap(List::stream).filter(e -> e.getDegree() == 1 || e.getDegree() == 2)
              .findAny()
              .orElse(null);

在这里,我们将ArrayList<ArrayList<Node>>转换为flatMap,然后根据您的条件应用过滤器。如果找到匹配项,则返回Node,否则返回null。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52918166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档