打印出两个set中差集_Java之两个Set集合的交集、差集和并集
一、求交集
注:場景是讀取兩個文件,把文件內(nèi)容放到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); }
總結(jié)
以上是生活随笔為你收集整理的打印出两个set中差集_Java之两个Set集合的交集、差集和并集的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 对某课程的建议和意见_2021年河南专升
 - 下一篇: 鸟归沙有迹的下一句是什么呢?