用java实现在 对两个文件数据取交集、并集、差集
- 以上代码首先读取了两个文件中的数据,然后使用 Java 集合类
HashSet
来存储集合中的元素。接着,我们使用 retainAll
、addAll
和 removeAll
等方法来对两个集合进行操作,求它们的交集、并集和差集。最后,我们将结果输出到控制台。 - 需要注意的是,在具体实现时,可能会遇到一些异常情况,比如文件不存在、IO异常等等,需要适当地进行处理。此外,如果要处理大规模的数据,可能需要考虑使用更高效的算法和数据结构来提高程序的性能。
代码:
import java.io.*;
import java.util.*;
public class SetOperations {
public static void main(String[] args) throws IOException {
// 读取文件1和文件2中的数据
Set<String> set1 = readDataFromFile("file1.txt");
Set<String> set2 = readDataFromFile("file2.txt");
// 对两个集合进行操作,求它们的交集、并集和差集
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
Set<String> difference1 = new HashSet<>(set1);
difference1.removeAll(set2);
Set<String> difference2 = new HashSet<>(set2);
difference2.removeAll(set1);
// 输出结果
System.out.println("Intersection of set1 and set2:");
System.out.println(intersection);
System.out.println("Union of set1 and set2:");
System.out.println(union);
System.out.println("Difference of set1 and set2:");
System.out.println(difference1);
System.out.println("Difference of set2 and set1:");
System.out.println(difference2);
}
/**
* 从文件中读取数据到一个集合中
*/
public static Set<String> readDataFromFile(String filename) throws IOException {
Set<String> set = new HashSet<>();
File file = new File(filename);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
set.add(line.trim());
}
reader.close();
return set;
}
}
package li.dong;
import java.io.*;
import java.sql.SQLOutput;
import java.util.*;
/**
* 用java实现在 对两个文件数据取交集、并集、差集
*/
public class SetOperations {
public static void main(String[] args) throws IOException {
// 读取文件1和文件2中的数据
Set<String> set1=readDataFromFile("D:\\CS\\Code\\IdeaCode\\Database_Test001\\src\\li\\dong\\file1.txt");
Set<String> set2=readDataFromFile("D:\\CS\\Code\\IdeaCode\\Database_Test001\\src\\li/dong/file2.txt");
// 对两个集合进行操作,求它们的交集、并集和差集
//交集
Set<String> intersection=new HashSet<>(set1);
intersection.retainAll(set2);
//并集
Set<String> union=new HashSet<>(set2);
union.addAll(set2);
//差集
Set<String> difference1=new HashSet<>(set1);
difference1.removeAll(set2);
Set<String> difference2=new HashSet<>(set2);
difference2.removeAll(set1);
//输出结果
System.out.print("文件1和文件2的交集为:");
System.out.println(intersection);
System.out.print("文件1和文件2的并集为:");
System.out.println(union);
System.out.print("文件1和文件2的差集为:");
System.out.println(difference1);
System.out.print("文件2和文件1的差集为:");
System.out.println(difference2);
}
/**
* @order:从文件中读取数据到一个集合中
* @param fileName
* @return
* @throws IOException
*/
public static Set<String> readDataFromFile(String fileName)throws IOException{
Set<String> set=new HashSet<>();
File file=new File(fileName);
BufferedReader bufferedReader=new BufferedReader(new FileReader((file)));
String line="";
while ((line=bufferedReader.readLine())!=null){
set.add(line.trim());
}
bufferedReader.close();
return set;
}
}