gpt4 book ai didi

java - 检查java中的List>中是否存在值?

转载 作者:行者123 更新时间:2023-11-29 04:27:40 26 4
gpt4 key购买 nike

我想检查 List<List<objects>> 中是否存在对象并返回 List<<>> 的索引如果找到对象。

例如:

List<List<Integer>> listOfLists = new ArrayList<>(); 
List<Integer> listOne = new ArrayList<>();
listOne.add(1);
listOne.add(9);
listOfLists.add(listOne);
List<Integer> listTwo = new ArrayList<>();
listTwo.add(5);
listTwo.add(7);
listOfLists.add(listTwo);

现在我想查找 9 是否存在,如果存在则返回它在 listoflists 中的索引 '0'是否应该对其进行任何修改以使其与自定义对象一起使用?

最佳答案

您可以使用流来检查列表中是否存在对象

boolean has = listOfLists.stream().anyMatch(e -> e.contains(Integer.valueOf(9)));

如果你找到任何匹配项,你可以获得索引

List<Integer> list = listOfLists.stream().filter(e -> e.contains(Integer.valueOf(9))).findAny().get();
int index = listOfLists.indexOf(list);

在此示例中,列表是通用的 <Integer>我正在寻找某个整数,即 Integer.valueOf(9)但您可以根据自己的目的进行调整...

关于java - 检查java中的List<List<objects>>中是否存在值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45455368/

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