我想计算集合之间的差异。使用 CollectionUtils.subtract() 进行自定义比较时,我需要覆盖对象的 equals() 方法。但是,如果我需要比较类型相同但比较标准不同的对象集合怎么办? Comparator 接口(interface)怎么样,它似乎非常适合这里? AFAIK Comparator 主要用于排序。有没有使用比较器做减法的方法?
最佳答案
static <Type> Collection<Type> subtract(Collection<Type> a, Collection<Type> b, Comparator<Type> c) {
Set<Type> subtrahend = new TreeSet<Type>(c);
subtrahend.addAll(b);
Collection<Type> result = new ArrayList<Type>();
for (Type item: a) {
if (!subtrahend.contains(item)) result.add(item);
}
return result;
}
subtrahent
树集不是必需的,但会提高大型 b
的性能。
关于java - 如何使用 Comparator 接口(interface)减去集合而不是覆盖 equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348054/