您的位置:首页 > 其它

高效找出两个List中不同的元素

2017-12-17 20:25 288 查看
原文链接:https://www.cnblogs.com/czpblog/archive/2012/08/06/2625794.html

建议看原文,有优化的步骤。

package com.why.until;

import java.util.*;

public class CollectionUtil {

private CollectionUtil() {
}

/**
*  获取两个集合的不同元素
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Collection getDiffent(Collection collmax,Collection collmin)
{
//使用LinkeList防止差异过大时,元素拷贝
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;
}
/**
*  获取两个集合的不同元素,去除重复
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Collection getDiffentNoDuplicate (Collection collmax,Collection collmin)
{
return new HashSet(getDiffent(collmax, collmin));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  优化