[英]Check if value exists in List<List<objects>> in java?
我想檢查List<List<objects>>
List<<>>
是否存在對象,如果找到該對象則返回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,即Integer.valueOf(9)
但你可以根據你的目的進行調整......
如果你可以使用番石榴:
return Iterables.indexOf(listOfLists, innerList -> innerList.contains(9));
這將返回找到的第一個對象的索引,如果未找到,則返回-1。
如果您的列表包含自定義對象而不是Integer,則代碼完全相同; 它依賴於具有正確定義的equals()
方法的自定義對象。
循環遍歷列表,如果包含,則返回索引
for(List<Integer> list : listoflists){
if(list.contains(9)){
return listoflists.indexOf(list);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.