1、取交集(取两个集合中都存在的元素) HashSet<String> setA =newHashSet<>();HashSet<String> setB =newHashSet<>();//用于存放结果HashSet<String> resSet =newHashSet<>(); resSet.addAll(setA); resSet.retainAll(setB);returnresSet; 2、取差集(取存在一个集合中,但不存在于另外一个集合中的元素...
JAVA集合Set交集、差集、并集/** * Created by yuhui on 2017/7/11 0011.*/ import java.util.HashSet;import java.util.Set;public class TestSet { public static void main(String[] args) { Set<String> result = new HashSet<String>();Set<String> set1 = new HashSet<String>() { { add(...
set2.add(5);// 使用retainAll()方法保留set1和set2的交集元素set1.retainAll(set2);// 输出交集结果System.out.println("交集: "+ set1); } } AI代码助手复制代码 差集(Difference): import java.util.HashSet; import java.util.Set;publicclassDifference{publicstaticvoidmain(String[] args){ Set<I...
TreeSet的数据结构可以理解为是二叉树数据结构,我们可以使用TreeSet实现排序功能,TreeSet通过定义一个比较容器Comparator来完成集合对象中的排序。 存储特点:有序,不重复;key不能为空,value可以为null(总结一点:凡是有Tree的集合,都是有序的,凡是有Set的就是不重复的) 五、交集差集并集的使用 1交集 对于两个给定集...
System.out.println("交集 = "+ result); result.clear(); result.addAll(set1); result.removeAll(set2); System.out.println("差集 = "+result); result.clear(); result.addAll(set1); result.addAll(set2); System.out.println("并集 = "+ result); ...
首先命名一个类名为DealSet存放查找并集,差集,交集的方法 DealSet.java package SetLearning; import java.util.HashSet; import java.util.Set;public class DealSet<T> { private Set<T> differentSet ; private Set<T> sameSet ; private Set<T> unionSet ; /* ...
Set 不允许重复元素,因此添加重复元素将被忽略。 Set 集合通常不保证元素的顺序,如果需要顺序,请考虑使用 LinkedHashSet 或TreeSet。 Set 集合不是线程安全的,如果在多线程环境中使用,需要考虑同步操作或使用线程安全的集合实现。 8. 高级用法 8.1 Set 集合的操作 Set 集合支持一系列集合操作,如并集、交集和差集。
集合中的(交集,并集,差集,补集,对称差集)老是会弄混了 常用的集合类有一下几种: List结构的集合类:ArrayList类,LinkedList类,Vector类,Stack类 Map结构的集合类:HashMap类,Hashtable类 Set结构的集合类:HashSet类,TreeSet类 Queue结构的集合:Queue接口 ...
Java之Set 交集,差集,并集 /** * Created by yuhui on 2017/7/11 0011. */importjava.util.HashSet;importjava.util.Set;publicclassTestSet{publicstaticvoidmain(String[] args) {Set<String> result =newHashSet<String>();Set<String> set1 =newHashSet<String>() { ...
交集Set<Integer>intersectionSet=newHashSet<>(set1);intersectionSet.retainAll(set2);System.out.println("交集:"+intersectionSet);// 并集Set<Integer>unionSet=newHashSet<>(set1);unionSet.addAll(set2);System.out.println("并集:"+unionSet);// 差集Set<Integer>differenceSet=newHashSet<>(set1);...