Java之两个Set集合的交集、差集和并集

时间:2025-04-24 06:57:31

一、求交集

注:场景是读取两个文件,把文件内容放到Set中,求两个文件之间的共同元素。在这里只写对Set的操作。

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set<String> set1 = readFile(path1);
		Set<String> set2 = readFile(path2);
		Set<String> set = new HashSet<String>();
		(set1);
		(set2);
		(set);
}

二、求差集

1)、获取在set1而不在set2中的元素

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set<String> set1 = readFile(path1);
		Set<String> set2 = readFile(path2);
		Set<String> set = new HashSet<String>();
		(set1);
		(set2);
		(set);
}

2)、获取在set2不在set1中的元素

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set<String> set1 = readFile(path1);
		Set<String> set2 = readFile(path2);
		Set<String> set = new HashSet<String>();
		(set2);
		(set1);
		(set);
}

三、求并集

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set<String> set1 = readFile(path1);
		Set<String> set2 = readFile(path2);
		Set<String> set = new HashSet<String>();
		(set2);
		(set1);
		(set);
}