一、功能描述
比较两个list中存储的map数据,比较的list的数据类型需一致,就能比较出存储的数据是否一致。
二、实现步骤
1、比较两个list的长度大小
2、统计出每个list中存储的map值的个数及重复的,进行比较
3、具体比较值
三、代码实例
private static final Integer INTEGER_ONE = 1;
// 判断并返回结果 true和false
public static boolean isEqualCollection(Collection a, Collection b) {
if (a.size() != b.size()) { // size是最简单的相等条件
return false;
}
Map mapa = getCardinalityMap(a);
System.out.println(mapa);
Map mapb = getCardinalityMap(b);
System.out.println(mapb);
// 转换map后,能去掉重复的,这时候size就是非重复项,也是先决条件
if (mapa.size() != mapb.size()) {
System.out.println("存储的map数据不一致!");
return false;
} else {
System.out.println("转换map后,能去掉重复的,这时候size就是非重复项后,存储的map数据一致!");
}
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;
}
/**
* 以obj为key,可以防止重复,如果重复就value++ 这样实际上记录了元素以及出现的次数
*/
public static Map getCardinalityMap(Collection coll) {
Map count = new HashMap();
for (Iterator it = coll.iterator(); it.hasNext();) {
Object obj = it.next();
Integer c = (Integer) count.get(obj);
if (c == null)
count.put(obj, INTEGER_ONE);
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;
}
// main方法测试类
public static void main(String[] args) {
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("a", "abc");
m1.put("b", "123");
m1.put("c", "123");
m1.put("d", "123");
Map<String, Object> m2 = new HashMap<String, Object>();
m2.put("c", "123");
m2.put("a", "abc");
m2.put("b", "123");
m2.put("d", "123");
Map<String, Object> m3 = new HashMap<String, Object>();
m3.put("a", "abc");
m3.put("b", "123");
m3.put("c", "123");
m3.put("d", "123");
Map<String, Object> m4 = new HashMap<String, Object>();
m4.put("b", "123");
m4.put("a", "abc");
m4.put("c", "123");
m4.put("d", "123");
List<Map<String, Object>> a = new ArrayList<>();
a.add(m1);
a.add(m3);
List<Map<String, Object>> b = new ArrayList<>();
b.add(m2);
b.add(m4);
boolean c = isEqualCollection(a, b);
System.out.println(c);
}
往期精彩内容:
原创不易,转载自:https://blog.csdn.net/qq_28245087/article/details/93187235