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

一、求交集

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

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set set1 = readFile(path1);
		Set set2 = readFile(path2);
		Set set = new HashSet();
		set.addAll(set1);
		set.retainAll(set2);
		System.out.println(set);
}

二、求差集

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

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set set1 = readFile(path1);
		Set set2 = readFile(path2);
		Set set = new HashSet();
		set.addAll(set1);
		set.removeAll(set2);
		System.out.println(set);
}

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

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set set1 = readFile(path1);
		Set set2 = readFile(path2);
		Set set = new HashSet();
		set.addAll(set2);
		set.removeAll(set1);
		System.out.println(set);
}

三、求并集

public static void main(String[] args) throws Exception {
		String path1 = "path1";
		String path2 = "path2";
		Set set1 = readFile(path1);
		Set set2 = readFile(path2);
		Set set = new HashSet();
		set.addAll(set2);
		set.addAll(set1);
		System.out.println(set);
}

 

你可能感兴趣的:(JavaSE)