求Map的交集、并集、差集
如果两个Map有相同的键,交集求最小值,并集求最大值。
public class HashMapTest {
// 求交集
private static Map<String,Integer> Intersection(Map<String,Integer> mp1, Map<String,Integer> mp2) {
List<String> strRemove = new ArrayList<String>();
Map<String,Integer> res = new HashMap<String,Integer>(mp1);
for (String s: res.keySet()){
if (!mp2.containsKey(s)) {//mp1中存在但mp2中不存在
strRemove.add(s);
}else{ //mp1中存在mp2中存在
res.put(s,Math.min(res.get(s),mp2.get(s)));
}
}
for (String s: strRemove) {
res.remove(s);
}
return res;
}
// 求并集
private static Map<String,Integer> Union(Map<String,Integer> mp1, Map<String,Integer> mp2) {
Map<String,Integer> res = new HashMap<String,Integer>(mp1);
for (String s: mp2.keySet()){
if (mp1.containsKey(s)) {//mp2中存在 mp1中存在
res.put(s,Math.max(mp1.get(s),mp2.get(s)));
}else{ //mp2中存在 mp1中不存在
res.put(s,mp2.get(s));
}
}
return res;
}
// 求差集
private static Map<String,Integer> Difference(Map<String,Integer> mp1, Map<String,Integer> mp2) {
List<String> strRemove = new ArrayList<String>();
Map<String,Integer> res = new HashMap<String,Integer>(mp1);
for (String s: res.keySet()) {
if (mp2.containsKey(s)){
strRemove.add(s);
}
}
for (String s: strRemove) {
res.remove(s);
}
return res;
}
// 计数 生成两个Map
private static Map<String,Integer> Counter(String string){
Map<String,Integer> mp = new HashMap<String,Integer>();
String[] strArray = string.split("");
int cnt;
for (String s:strArray){
cnt = mp.getOrDefault(s,0);
mp.put(s,cnt+1);
}
return mp;
}
// 调用
public static void main(String[] args){
//求两个HashMap的交集、差集、并集
String str1 = "queue";
String str2 = "upper";
// 统计每个元素的出现次数
Map<String,Integer> mp1 = new HashMap<String,Integer>();
Map<String,Integer> mp2 = new HashMap<String,Integer>();
mp1 = Counter(str1);
mp2 = Counter(str2);
System.out.println("mp1"+mp1);
System.out.println("mp2"+mp2);
// 求交集
Map<String,Integer> resultIntersection = new HashMap<String,Integer>();
resultIntersection = Intersection(mp1, mp2);
System.out.println("交集:"+resultIntersection);
//求并集
Map<String,Integer> resultUnion = new HashMap<String,Integer>();
resultUnion = Union(mp1, mp2);
System.out.println("并集:"+resultUnion);
//求差集
Map<String,Integer> resultDifference = new HashMap<String,Integer>();
resultDifference = Difference(mp1, mp2);
System.out.println("差集mp1-mp2:"+resultDifference);
}
}