工具类完整代码
public class CollectionUtil {
private CollectionUtil() {
}
/**
* 找出两个集合中不同的元素
*
* @param collmax
* @param collmin
* @return
*/
public static Collection getDifferent(Collection collmax, Collection collmin) {
//使用LinkedList防止差异过大时,元素拷贝
Collection csReturn = new LinkedList();
Collection max = collmax;
Collection min = collmin;
//先比较大小,这样会减少后续map的if判断次数
if (collmax.size() < collmin.size()) {
max = collmin;
min = collmax;
}
//直接指定大小,防止再散列
Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
for (Object object : max) {
map.put(object, 1);
}
for (Object object : min) {
if (map.get(object) == null) {
csReturn.add(object);
} else {
map.put(object, 2);
}
}
for (Map.Entry<Object, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
csReturn.add(entry.getKey());
}
}
return csReturn;
}
/**
* 找出两个集合中相同的元素
*
* @param collmax
* @param collmin
* @return
*/
public static Collection getSame(Collection collmax, Collection collmin) {
//使用LinkedList防止差异过大时,元素拷贝
Collection csReturn = new LinkedList();
Collection max = collmax;
Collection min = collmin;
//先比较大小,这样会减少后续map的if判断次数
if (collmax.size() < collmin.size()) {
max = collmin;
min = collmax;
}
//直接指定大小,防止再散列
Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
for (Object object : max) {
map.put(object, 1);
}
for (Object object : min) {
if (map.get(object) != null) {
csReturn.add(object);
}
}
return csReturn;
}
/**
* 获取两个集合的不同元素,去除重复
*
* @param collmax
* @param collmin
* @return
*/
public static Collection getDiffentNoDuplicate(Collection collmax, Collection collmin) {
return new HashSet(getDifferent(collmax, collmin));
}
}
测试代码,两个list分别添加了100万条数据和199万条数据
获取两个list中不同的元素
public static void main(String[] args) throws Exception {
List<Integer> num1 = new ArrayList<>();
List<Integer> num2 = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
num1.add(i);
}
for (int i = 19999; i < 2009999; i++) {
num2.add(i);
}
System.out.println("num1长度:" + num1.size());
System.out.println("num2长度:" + num2.size());
long startTime = System.currentTimeMillis();
Collection different = CollectionUtil.getDifferent(num1, num2);
System.out.println("共耗时:" + (System.currentTimeMillis() - startTime) + "毫秒");
System.out.println("不同元素共有:" + different.size());
}
输出:
num1长度:1000000
num2长度:1990000
共耗时:202毫秒
不同元素共有:1029998
获取两个list中相同的元素
public static void main(String[] args) throws Exception {
List<Integer> num1 = new ArrayList<>();
List<Integer> num2 = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
num1.add(i);
}
for (int i = 19999; i < 2009999; i++) {
num2.add(i);
}
System.out.println("num1长度:" + num1.size());
System.out.println("num2长度:" + num2.size());
long startTime2 = System.currentTimeMillis();
Collection same = CollectionUtil.getSame(num1, num2);
System.out.println("共耗时:" + (System.currentTimeMillis() - startTime2) + "毫秒");
System.out.println("相同元素共有:" + same.size());
}
输出:
num1长度:1000000
num2长度:1990000
共耗时:148毫秒
相同元素共有:980001