集合的交、并、差集操作及扩展(对两个数据源的信息进行合并根据key)
测试代码
public class SetHandleTest {
//差集:以属于A而不属于B的元素为元素的集合称为A与B的差(集)
public static void main(String[] args) {
//baseHandle();
mergeInfoByKey();
}
/**
* 集合的交、并、差集
*/
//TreeSet和LinkedHashSet的区别
private static void baseHandle(){
//1 准备基础数据,如果要按添加顺序排列,使用 LinkedHashSet
Set setOne = new HashSet<>();
setOne.add("钱二");
setOne.add("张三");
setOne.add("李四");
Set setTwo = new TreeSet<>();
setTwo.add("李四");
setTwo.add("王五");
setTwo.add("赵六");
//2 对集合进行操作
//2.1 取并集
//setOne.addAll(setTwo);
//System.out.println(setOne);
//结果: [张三, 李四, 王五, 赵六, 钱二]
//2.2 取交集
//setOne.retainAll(setTwo);
//System.out.println(setOne);
//结果: [李四]
//2.3 取一和二的差集(保留一集合中与二集合不同的元素)
setOne.removeAll(setTwo);
System.out.println(setOne);
//结果: [张三, 钱二]
}
/**
* 合并两个数据来源的信息(相同key的,信息汇总,其他的保留原有的信息)
*/
private static void mergeInfoByKey(){
//1 准备基础数据
Map mapA= new HashMap<>();
mapA.put(1L,"1A");
mapA.put(2L,"1A");
mapA.put(3L,"1A");
Map mapB = new HashMap<>();
mapB.put(1L,"1B");
mapB.put(12L,"1B");
mapB.put(13L,"1B");
//2 定义返回对象收集器
Map resultMap = new HashMap<>();
//3 判断
//3.1 都不为空,两个信息源的信息合并(关键点)
if (!CollectionUtils.isEmpty(mapA)&&!CollectionUtils.isEmpty(mapB)){
//3.1.1 准备进行交,差集操作的集合
Set setOneA = new HashSet<>(mapA.keySet());
Set setTwoA = new HashSet<>(mapA.keySet());
Set setThreeA = new HashSet<>(mapA.keySet());
Set setOneB = new HashSet<>(mapB.keySet());
Set setTwoB = new HashSet<>(mapB.keySet());
Set setThreeB = new HashSet<>(mapB.keySet());
//取交集
setOneA.retainAll(setOneB);
System.out.println(setOneA);
//取a和b的差集
setTwoA.removeAll(setTwoB);
//System.out.println(setTwoA);
//取b和a的差集
setThreeB.removeAll(setThreeA);
//System.out.println(setThreeB);
//信息合并
for (Long key : setOneA) {
String value=mapA.get(key)+":"+mapB.get(key);
resultMap.put(key,value);
}
for (Long key : setTwoA) {
resultMap.put(key,mapA.get(key));
}
for (Long key : setThreeB) {
resultMap.put(key,mapB.get(key));
}
}
//3.2 b信息源为空,a信息源不为空,那么只要a信息源的
if (!CollectionUtils.isEmpty(mapA)&&CollectionUtils.isEmpty(mapB)){
resultMap.putAll(mapA);
}
//3.2 a信息源为空,b信息源不为空,那么只要b信息源的
if (CollectionUtils.isEmpty(mapA)&&!CollectionUtils.isEmpty(mapB)){
resultMap.putAll(mapB);
}
for (Map.Entry entry : resultMap.entrySet()) {
System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
}
}