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
{
}
}
添加回答
举报