CollectionUtils.isEqualCollection的用法

在使用Java的集合时,有些时候会需要比较两个集合是否相等,自己写方法其实也简单,但是既然有了好的实现,就不要自己造轮子了,只要了解这个轮子是什么原理就好了。

public static boolean isEqualCollection(final Collection<?> a, final Collection<?> b)

 

传入两个Collection就可以了,我们常用的List或者Set,根据源码发现:

这个方法比较的是集合中的元素以及元素的个数,不管是List或者是Set,不要求顺序相同。

下面是一个例子,其中的源码可能因为版本更迭与最新的不同,但是原理是一样的:

package collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;

public class Test1 {

	// CollectionUtils.isEqualCollection
	/**
	 * isEqualCollection
	 * 
	 * public static <E> boolean isEqualCollection(Collection<E> a, Collection<E> b) Returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities.
	 * That is, iff the cardinality of e in a is equal to the cardinality of e in b, for each element e in a or b.
	 * 
	 * Parameters: 
	 * 		a - the first collection, must not be null 
	 * 		b - the second collection, must not be null 
	 * Returns: 
	 * 		true iff the collections contain the same elements with the same cardinalities.
	 * 
	 */
	@Test
	public void test1() {
		ArrayList<String> arr1 = new ArrayList<String>();
		arr1.add("1");
		arr1.add("2");
		arr1.add("2");
		arr1.add("3");
		arr1.add("4");
		arr1.add("5");
		ArrayList<String> arr2 = new ArrayList<String>();
		arr2.add("1");
		arr2.add("1");
		arr2.add("2");
		arr2.add("3");
		arr2.add("5");
		arr2.add("4");
		System.out.println(CollectionUtils.isEqualCollection(arr1, arr2));
		
		// copy的源码
		System.out.println(isEqualCollection(arr1, arr2));
	}

	public static boolean isEqualCollection(Collection a, Collection b) {
		if (a.size() != b.size())
			return false;
		Map mapa = getCardinalityMap(a);
		Map mapb = getCardinalityMap(b);
		if (mapa.size() != mapb.size())
			return false;
		for (Iterator it = mapa.keySet().iterator(); it.hasNext();) {
			Object obj = it.next();
			if (getFreq(obj, mapa) != getFreq(obj, mapb))
				return false;
		}

		return true;
	}

	private static Integer INTEGER_ONE = new Integer(1);

	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();
		else
			return 0;
	}
}

转载于:https://www.cnblogs.com/huangwenjie/p/6648322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值