我如何比较两个数组列表与自定义比较器的相等? [英] How can I compare two array lists for equality with a custom comparator?
问题描述
具体来说,我有两个列表:
To be specific, I have two lists:
List<SystemUserWithNameAndId> list1;
List<SystemUserWithNameAndId> list2;
我想检查它们是否包含相同的系统用户,并且订购不是问题。我试图使用比较器首先对它们进行排序,然后使用列表的equals()方法检查它们是否相等。但是我不想覆盖SystemUserWithNameAndId的equals方法,我想知道我是否可以使用为排序创建的比较器或类似的比较器来检查是否相等,无需在排序后显式地遍历列表。
I want to check if they contain the same system users and ordering is not an issue. I tried to use a comparator to sort them first and then check if they're equal using the equals() method of lists. But I don't want to override the equals method for SystemUserWithNameAndId and I was wondering if I could use the comparator I created for sorting or a similar one to check for equality without explicitly iterating through the lists after sorting.
Comparator<SystemUserWithNameAndId> systemUserComparator = new Comparator<SystemUserWithNameAndId>()
{
@Override
public int compare(SystemUserWithNameAndId systemUser1, SystemUserWithNameAndId systemUser2)
{
final int systemUserId1 = systemUser1.getSystemUserId();
final int systemUserId2 = systemUser2.getSystemUserId();
return systemUserId1 == systemUserId2
? 0
: systemUserId1 - systemUserId2;
}
};
Collections.sort(systemUsers1, systemUserComparator);
Collections.sort(systemUsers2, systemUserComparator);
return systemUsers1.equals(systemUsers2);
理想情况下,我想能够说:
Ideally, I want to be able to say,
CollectionUtils.isEqualCollections(systemUsers1, systemUsers2, someCustomComparator);
推荐答案
只要实现迭代的方法,时间您需要它:
Just implement the method that iterates, and reuse it every time you need it:
public static <T> boolean areEqualIgnoringOrder(List<T> list1, List<T> list2, Comparator<? super T> comparator) {
// if not the same size, lists are not equal
if (list1.size() != list2.size()) {
return false;
}
// create sorted copies to avoid modifying the original lists
List<T> copy1 = new ArrayList<>(list1);
List<T> copy2 = new ArrayList<>(list2);
Collections.sort(copy1, comparator);
Collections.sort(copy2, comparator);
// iterate through the elements and compare them one by one using
// the provided comparator.
Iterator<T> it1 = copy1.iterator();
Iterator<T> it2 = copy2.iterator();
while (it1.hasNext()) {
T t1 = it1.next();
T t2 = it2.next();
if (comparator.compare(t1, t2) != 0) {
// as soon as a difference is found, stop looping
return false;
}
}
return true;
}
这篇关于我如何比较两个数组列表与自定义比较器的相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!