public class ListUtils {
/**
* 判断集合元素是否相等(无序)
*/
public static boolean isEqualCollection(Collection a, Collection b){
if (a.size() !=b.size()) { // size是最简单的相等条件
return false;
}
Map mapa = getCardinalityMap(a);
Map mapb = getCardinalityMap(b);
// 转换map后,能去掉重复的,这时候size就是非重复项,也是先决条件
if (mapa.size() !=mapb.size()) {
return false;
}
Iterator it =mapa.keySet().iterator();
while (it.hasNext()) {
Object obj = it.next();
// 查询同一个obj,首先两边都要有,而且还要校验重复个数,就是map.value
if (getFreq(obj,mapa) != getFreq(obj, mapb)) {
return false;
}
}
return true;
}
public static Map getCardinalityMap(Collection coll) {
Map count = new HashMap();
Iterator it = coll.iterator();
for (it.hasNext()) {
Object obj =it.next();
Integer c =(Integer) count.get(obj);
if (c == null)
count.put(obj, 1);
else {
count.put(obj, new Integer(c.intValue() + 1));
}
}
return count;
}
private static final int getFreq(Object obj, Map freqMap) {
Integer count =(Integer) freqMap.get(obj);
if (count != null) {
return count.intValue();
}
return 0;
}
}
6.判断list集合中元素是否相等(无序)
最新推荐文章于 2024-07-03 12:46:25 发布