一、交集
//交集@Testpublic void intersection(){//向集合中添加元素ArrayList<String> datas = new ArrayList<>();Collections.addAll(datas, "张三", "李四", "王五", "赵六");//向集合中添加元素ArrayList<String> arrs = new ArrayList<>();Collections.addAll(arrs, "田七", "赵六", "张三", "阿飞");// 求交集datas.retainAll(arrs);for (String str : datas) {System.out.println(str);}}
二、并集
//并集@Testpublic void union(){ArrayList<String> datas = new ArrayList<>();//向集合中添加元素Collections.addAll(datas, "张三", "李四", "王五", "赵六");//向集合中添加元素ArrayList<String> arrs = new ArrayList<>();Collections.addAll(arrs, "田七", "赵六", "张三", "阿飞");// 求并集datas.removeAll(arrs);//先从本集合中删除另一个集合中相同的元素datas.addAll(arrs);//再把另外一个集合中所有元素,添加到本集合中for (String str : datas) {System.out.println(str);}}
三、差集
//差集:两个集合排除相同的剩余部分!@Testpublic void DifferenceSet(){ArrayList<String> datas = new ArrayList<>();//向集合中添加元素Collections.addAll(datas, "张三", "李四", "王五", "赵六");//向集合中添加元素ArrayList<String> arrs = new ArrayList<>();Collections.addAll(arrs, "田七", "赵六", "张三", "阿飞");// 求差集 张三,李四,王五 ,赵六 | 田七,赵六,张三 ,阿飞 ---> 李四,王五,田七,阿飞ArrayList<String> list = (ArrayList<String>) datas.clone();// 张三,李四,王五 ,赵六datas.removeAll(arrs);// datas 李四,王五arrs.removeAll(list);// arrs 田七,阿飞datas.addAll(arrs);// 李四,王五,田七,阿飞for (String str : datas) {System.out.println(str);}}
四、补集
//补集@Testpublic void Complement(){ArrayList<String> aList = new ArrayList<>();//向集合中添加元素Collections.addAll(aList, "1", "2", "3", "4");//向集合中添加元素ArrayList<String> bList = new ArrayList<>();Collections.addAll(bList, "2", "4", "5", "6");ArrayList<String> cList = (ArrayList<String>) aList.clone();cList.retainAll(bList);System.out.println("A 与 B 交集:" + cList);bList.removeAll(cList);System.out.println("A 关于 B 的相对补集:" + bList);aList.removeAll(cList);System.out.println("B 关于 A 的相对补集:" + aList);}