使用自定义相等函数检查两个集合是否相同(忽略顺序)

时间:2015-10-15 01:21:44

标签: java guava equality

我有两个Foo系列。我无法改变Foo的实现,而Foo的equals函数实现不正确。我也不能继承Foo。我做自定义相等功能:我已经使用guava的Predicate函数实现了。为了给你一个想法,实现看起来有点像这样。

new Predicate<Pair<Foo, Foo>>() {
        @Override
        public boolean apply(@Nullable Pair<Foo, Foo> input) {
          Foo one = input.getFirst();
          Foo two = input.getSecond();
          return Objects.equals(one.getId(), two.getId());
        }
      };

现在我需要检查我的两个Foo系列是否包含相同的项忽略顺序

我正在寻找使用此自定义相等函数执行此操作的最佳方法。

3 个答案:

答案 0 :(得分:5)

您可以将您的课程包装在番石榴Equivalence中并将其存储在集合中。

Equivalence<Foo> eq = new Equivalence<Foo>{
// implement equals and hashcode
};
Set<Equivalence<Foo>> set1 = new HashSet<>();
set1.add(eq.wrap(someFoo));

这样你可以做双向containsAll()或做

Sets.difference(set1, set2).isEmpty()

答案 1 :(得分:1)

为什么不是自定义Predicate的简单SortedSet,而不是自定义Comparator

    Comparator<Foo> comparator = new Comparator<Foo>() {

        public int compare(Foo o1, Foo o2) {
            return //your custom comparison
        }
    };
    SortedSet<Foo> sortedSet1 = newTreeSet(comparator);
    sortedSet1.addAll(firstCollection);
    SortedSet<Foo> sortedSet2 = newTreeSet(comparator);
    sortedSet2.addAll(secondCollection);

    sortedSet1.equals(sortedSet); //this is what you want

答案 2 :(得分:-2)

如果您不希望在操作后排序列表,请复制它或使用Set的答案(但Set [1,1,1] == [1])。< / p>

public class ListTest {
    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5);
        List<Integer> list3 = Arrays.asList(1, 2, 3, 4, 4);

        System.out.println(compare(list1, list2, (a, b) -> a - b));
        System.out.println(compare(list1, list3, (a, b) -> a - b));
    }

    private static <E> boolean compare(List<E> list1, List<E> list2, Comparator<E> comparator) {
        if(list1.size() != list2.size()) {
            return false;
        }
        Collections.sort(list1, comparator);
        Collections.sort(list2, comparator);
        Iterator<E> iterator1 = list1.iterator();
        Iterator<E> iterator2 = list2.iterator();
        while (iterator1.hasNext()) {
            if(comparator.compare(iterator1.next(), iterator2.next()) != 0) {
                return false;
            }
        }
        return true;
    }
}