Set 求交集、并集、差集
程序员文章站
2022-06-12 19:59:36
...
项目中经常遇到需要求两个集合的并集的情况,每次都要度娘,永远记不住????????????,所以干脆自己记下来。
直接上代码:
/**
* fshows.com
* Copyright (C) 2013-2019 All Rights Reserved.
*/
package com.fshows.lifecircle.marketcore.common.util;
import com.google.common.collect.Sets;
import java.util.Set;
/**
* @author liuyuan
* @version Test.java, v 0.1 2019-12-31 11:27
*/
public class Test {
public static void main(String[] args) {
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
Set<String> set1 = Sets.newHashSet();
set1.add(s1);
set1.add(s2);
Set<String> set2 = Sets.newHashSet();
set2.add(s2);
set2.add(s3);
// 求交集
Set intersect = getIntersect(set1, set2);
// 执行结果:[s2]
System.out.println(intersect);
// 求并集
Set unite = getUnite(set1, set2);
// 执行结果:[s3, s1, s2]
System.out.println(unite);
// 求差集
Set subtract = getSubtract(set1, set2);
// 执行结果:[s1]
System.out.println(subtract);
}
/**
* 求交集
*/
private static Set getIntersect(Set<?> set1, Set<?> set2) {
Set<Object> set = Sets.newHashSet();
set.addAll(set1);
set.retainAll(set2);
return set;
}
/**
* 求并集
*/
private static Set getUnite(Set<?> set1, Set<?> set2) {
Set<Object> set = Sets.newHashSet();
set.addAll(set1);
set.addAll(set2);
return set;
}
/**
* 求差集 set1 - set2
*/
private static Set getSubtract(Set<?> set1, Set<?> set2) {
Set<Object> set = Sets.newHashSet();
set.addAll(set1);
set.removeAll(set2);
return set;
}
}
上一篇: 微信 61501
下一篇: 微信支付支付结果通知处理