使用场景:
list 可以对比两个list 那些是重复的 那些是不重复的,直接把 500 个船名放到list 里面 然后再把 指挥系统查出来的400个船名放到新的list 里面 然后掉一个方法能对比出来两个list 交际 差集 并集
java
public static List<String> findNonIntersection(List<String> list1, List<String> list2) {
List<String> difference = new ArrayList<>(list1);
difference.removeAll(list2);//移除list1里面相同元素 得到差集
return difference;
}
public static void main(String[] args) {
List<String> list1 = Arrays.asList("1", "2", "3", "4", "5");
List<String> list2 = Arrays.asList("1", "2", "4");
List<String> nonIntersection = findNonIntersection(list1, list2);
System.out.println("没有交集的部分:" + nonIntersection);
}
实际应用:
java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ShipNameComparison {
public static void main(String[] args) {
// 模拟500个船名
List<String> shipNamesList1 = new ArrayList<>();
for (int i = 1; i <= 500; i++) {
shipNamesList1.add("Ship" + i);
}
// 模拟400个船名
List<String> shipNamesList2 = new ArrayList<>();
for (int i = 250; i <= 650; i++) {
shipNamesList2.add("Ship" + i);
}
// 获取交集、差集和并集
Set<String> intersection = getIntersection(shipNamesList1, shipNamesList2);
Set<String> difference1 = getDifference(shipNamesList1, shipNamesList2);
Set<String> difference2 = getDifference(shipNamesList2, shipNamesList1);
Set<String> union = getUnion(shipNamesList1, shipNamesList2);
// 输出结果
System.out.println("交集: " + intersection);
System.out.println("船名在List1但不在List2的差集: " + difference1);
System.out.println("船名在List2但不在List1的差集: " + difference2);
System.out.println("并集: " + union);
}
// 获取交集
public static Set<String> getIntersection(List<String> list1, List<String> list2) {
Set<String> set1 = new HashSet<>(list1);
Set<String> set2 = new HashSet<>(list2);
set1.retainAll(set2); // 保留set1中也存在于set2中的元素
return set1;
}
// 获取差集
public static Set<String> getDifference(List<String> list1, List<String> list2) {
Set<String> set1 = new HashSet<>(list1);
Set<String> set2 = new HashSet<>(list2);
set1.removeAll(set2); // 移除set1中也存在于set2中的元素
return set1;
}
// 获取并集
public static Set<String> getUnion(List<String> list1, List<String> list2) {
Set<String> unionSet = new HashSet<>(list1);
unionSet.addAll(list2); // 添加list2的所有元素
return unionSet;
}
}