java匹配两个数组除了双重for循环还能怎么写
除了双重for循环,还可以使用Java 8的Stream API来匹配两个数组。可以使用Stream的filter、anyMatch和toArray方法来实现。
下面是一个示例代码:
import java.util.Arrays;
public class ArrayMatcher {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {3, 4, 5, 6, 7};
boolean hasCommonElement = Arrays.stream(array1)
.filter(x -> Arrays.stream(array2).anyMatch(y -> y == x))
.toArray().length > 0;
System.out.println(hasCommonElement);
}
}
这个示例中,首先使用Arrays.stream方法将数组转换为一个Stream对象。然后使用filter方法过滤掉在第二个数组中不存在的元素。接着使用anyMatch方法检查是否存在匹配的元素。最后使用toArray方法将结果转换为一个数组。如果最终的数组长度大于0,则说明两个数组有公共元素。
注意,使用Stream API的方法仅适用于Java 8及以上的版本
原文地址: http://www.cveoy.top/t/topic/iztr 著作权归作者所有。请勿转载和采集!