package com.zkdj.shiro.utils;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
public class CollectionUtil {
private CollectionUtil() {
}
/**
* 找出第一个集合中不存在与第二个集合的元素
*
* @param collmax
* @param collmin
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
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());
}
}
Iterator<String> it = csReturn.iterator() ;
while(it.hasNext()) {
String str = it.next() ;
if(str.equals(" ")||str.equals("")) {
it.remove();//此处删除集合中的一个元素
}
}
return csReturn;
}
/**
* 找出两个集合中相同的元素
*
* @param collmax
* @param collmin
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
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
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Collection getDiffentNoDuplicate(Collection collmax, Collection collmin) {
return new HashSet(getDifferent(collmax, collmin));
}
}
本文介绍了一个实用的集合操作工具类,包含找出两个集合之间的不同元素、相同元素以及去除重复的不同元素的功能。通过高效的算法实现,适用于Java开发中常见的集合操作需求。
1580

被折叠的 条评论
为什么被折叠?



