gpt4 book ai didi

java流操作检查并返回特定对象

转载 作者:行者123 更新时间:2023-11-30 02:00:46 24 4
gpt4 key购买 nike

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

所以我的例子如下:

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

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

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循环很容易解决问题,但我想要一个使用流api的解决方案。

我尝试过的:

 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应该是final的,但在我的例子中,我试图修改它。

有没有更好的解决办法?

最佳答案

这应该可以解决问题:

lists.stream().flatMap(List::stream).filter(e -> e.getDegree() == 1 || e.getDegree() == 2)
.findAny()
.orElse(null);

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

关于java流操作检查并返回特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com