4 回答

TA貢獻1900條經驗 獲得超5個贊
您可以只使用 Java Streams 來解決這個問題:
boolean good = val1.stream().anyMatch(val2::contains);
如果你需要第一個匹配的值,你可以使用這個:
Optional<String> firstMatch = val1.stream() .filter(val2::contains) .findFirst();
用于Optional.isPresent()
檢查是否找到匹配項并Optional.get()
獲取實際值。
要提高大型列表的性能,請使用集合 for val2
。的時間復雜度為O (1)Set.contains()
。

TA貢獻1845條經驗 獲得超8個贊
也許您想使用流
List<String> list1 = Arrays.asList("a","b","c","d","e");
List<String> list2 = Arrays.asList("b","e");
//gets the list of common elments
List<String> common = list1.stream().filter(s -> list2.contains(s)).collect(Collectors.toList());
if (common.isEmpty()) {
System.out.println("no common elements");
}else {
System.out.println("common elements");
common.forEach(System.out::println);
}
//just the check if any equal elements exist
boolean commonElementsExist = list1.stream().anyMatch(s -> list2.contains(s));
//3rd version get the first common element
Optional<String> firstCommonElement = list1.stream().filter(s -> list2.contains(s)).findFirst();
if(firstCommonElement.isPresent()) {
System.out.println("the first common element is "+firstCommonElement.get());
}else {
System.out.println("no common elements");
}

TA貢獻1803條經驗 獲得超3個贊
如果其中一個數組列表小于您應該在 for 循環中使用該特定列表的大小。
for(int i = 0; i < 1Val.size(); i++){
if(2val.contains(1Val.get(i))){
return true; // common value found
}
}
return false; // common value not found

TA貢獻1799條經驗 獲得超9個贊
試試這個代碼
for (int i=0;i<arrayList2.size();i++) {
for (int j=0;j<arrayList1.size(); j++) {
if(al2.get(i)equals(al1.get(j))){
// do something// you can add them to the new arraylist to process further or type break; to break from the loop
{
}
}
添加回答
舉報