取得两个集合中不同元素(去除两个集合中的相同元素)

/**
* 获取两个集合的不同元素

* @param collmax
* @param collmin
* @return
*/
@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); //保存集合1中的所有元素
}
for (Object object : min)
{
if (map.get(object) == null)
{
csReturn.add(object); //保存集合1中不存在的集合2的元素
} else
{
map.put(object, 2); //用集合2的元素覆盖集合1、集合2中的元素,此时所有value=1的元素则是集合1独有的元素
}
}


//将value=1的元素添加到集合中,至此,则得到了集合1、集合2中所有的不同元素
for (Map.Entry<Object, Integer> entry : map.entrySet())
{
if (entry.getValue() == 1)
{
csReturn.add(entry.getKey());
}
}
return csReturn;

}



原文:http://www.cnblogs.com/czpblog/archive/2012/08/06/2625794.html







猜你喜欢

转载自blog.csdn.net/frinder/article/details/8931559
今日推荐