如果你希望在两个 List 中找到任意一个交集元素即算成功,你可以使用一些适用于这种情况的方法,而不必找出所有的交集元素。以下是几种处理方式:
- 使用
contains()
方法: 遍历一个 List,检查每个元素是否存在于另一个 List 中。如果找到任何一个交集元素,就算成功。
List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<>(Arrays.asList("B", "C", "D"));
boolean foundIntersection = false;
for (String item : list1) {
if (list2.contains(item)) {
foundIntersection = true;
break;
}
}
if (foundIntersection) {
System.out.println("Intersection found!");
} else {
System.out.println("No intersection found.");
}
- 使用
Set
数据结构: 将一个 List 转换为 Set 数据结构,然后遍历另一个 List,在 Set 中查找是否存在交集元素。
List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<>(Arrays.asList("B", "C", "D"));
Set<String> set1 = new HashSet<>(list1);
boolean foundIntersection = false;
for (String item : list2) {
if (set1.contains(item)) {
foundIntersection = true;
break;
}
}
if (foundIntersection) {
System.out.println("Intersection found!");
} else {
System.out.println("No intersection found.");
}
使用 Stream API: 使用 Stream API 遍历一个 List,使用 anyMatch()
方法查找是否存在交集元素。
List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<>(Arrays.asList("B", "C", "D"));
boolean foundIntersection = list1.stream()
.anyMatch(list2::contains);
if (foundIntersection) {
System.out.println("Intersection found!");
} else {
System.out.println("No intersection found.");
}
你以为这就完了???到这里只能算是完成了,下面追求一下完美
考虑一个问题,上面stream的方式,如果list2数据量很大(或者比list1相比很大)怎么办,这个效率会怎么样呢?结合数据结构知识哪个查询负责度低,肯定是Map了吧,顺着思路调整一下
List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C"));
List<String> list2 = new ArrayList<>(Arrays.asList("B", "C", "D"));
Set<String> set2 = new HashSet<>(list2); // 将 list2 转换为 Set
boolean foundIntersection = list1.stream()
.anyMatch(set2::contains);
if (foundIntersection) {
System.out.println("Intersection found!");
} else {
System.out.println("No intersection found.");
}
//在这种写法中,我们将 list2 转换为 HashSet,这样在执行 set2::contains 操作时,查找的速度会更快,因为 HashSet 的查找时间复杂度是常数时间。这种方式比直接使用 list2::contains 更有效率,尤其是当 list2 的数量较大时。