用Java语言实现两个表(分别为R表和S表,表内数据用a,b,c表示)的差并交集并输出到文本
时间: 2024-05-10 21:17:30 浏览: 105
用JAVA编写的有关输出乘法表的程序
5星 · 资源好评率100%
假设R表和S表都有同样的三个字段a、b、c,并且两个表中的数据都是唯一的,以下是Java语言实现两个表的差、并、交集并输出到文本的代码示例:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class TableOperations {
public static void main(String[] args) {
// R表和S表的数据可以手动初始化,或者从文件中读取
String[][] rData = {{"1", "a", "x"}, {"2", "b", "y"}, {"3", "c", "z"}};
String[][] sData = {{"2", "b", "y"}, {"3", "c", "w"}, {"4", "d", "v"}};
// 求并集
Set<String[]> unionSet = new HashSet<>();
for (String[] rRow : rData) {
unionSet.add(rRow);
}
for (String[] sRow : sData) {
unionSet.add(sRow);
}
// 求交集
Set<String[]> intersectionSet = new HashSet<>();
for (String[] rRow : rData) {
for (String[] sRow : sData) {
if (rRow[0].equals(sRow[0]) && rRow[1].equals(sRow[1]) && rRow[2].equals(sRow[2])) {
intersectionSet.add(rRow);
}
}
}
// 求差集
Set<String[]> differenceSet = new HashSet<>();
for (String[] rRow : rData) {
boolean found = false;
for (String[] sRow : sData) {
if (rRow[0].equals(sRow[0]) && rRow[1].equals(sRow[1]) && rRow[2].equals(sRow[2])) {
found = true;
break;
}
}
if (!found) {
differenceSet.add(rRow);
}
}
// 将结果输出到文件
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("并集:\n");
for (String[] row : unionSet) {
writer.write(row[0] + "," + row[1] + "," + row[2] + "\n");
}
writer.write("\n交集:\n");
for (String[] row : intersectionSet) {
writer.write(row[0] + "," + row[1] + "," + row[2] + "\n");
}
writer.write("\n差集:\n");
for (String[] row : differenceSet) {
writer.write(row[0] + "," + row[1] + "," + row[2] + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们使用了Java的Set集合来求并集、交集和差集。由于Set集合中不允许有重复元素,因此可以保证最终的结果中不会有重复的行数据。最后,我们将结果输出到文件中,以便查看和比较。
阅读全文