Java求交集和并集
package org.jerval.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List list1 = Arrays.asList(1, 2, 3, 4, 5, 6);
List list2 = Arrays.asList(6, 7);
List list3 = Arrays.asList(4, 5, 6, 7, 8, 9);
System.out.println(getIntersection(list1, list2, list3));
System.out.println(getUnionSet(list1, list2, list3));
}
// 求交集
private static List getIntersection(List... list) {
Set set = new HashSet();
Map map = new HashMap();
if (null != list) {
Integer cnt = null;
for (List listInner:list) {
if (null != listInner) {
for (E item:listInner) {
cnt = map.get(item);
if (null == cnt) {
map.put(item, 1);
} else {
map.put(item, cnt + 1);
}
}
}
}
int size = list.length;
for (Entry item:map.entrySet()) {
if (size == item.getValue()) {
set.add(item.getKey());
}
}
}
return new ArrayList(set);
}
// 求并集,利用Set来过滤相同元素。
private static List getUnionSet(List... list) {
Set set = new HashSet();
if (null != list) {
for (List listInner:list) {
if (null != listInner) {
for (E item:listInner) {
set.add(item);
}
}
}
}
return new ArrayList(set);
}
}