2015-10-15 27 views
1

我有两个Foo集合。我无法更改Foo的实现,而Foo的equals函数执行不正确。我也不能从Foo继承。我做自定义相等函数:我已经实现了使用番石榴的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()); 
     } 
     }; 

现在,我需要检查,如果我富的两个集合包含相同的项目忽略使用此自定义功能的平等我正在寻找最好的方式顺序

做到这一点。

+1

您可以使用集吗?否则,你可以从list1中检查list2'containsAll'项目,反之亦然。 – mvd

+0

我知道的Set的任何实现都使用equals函数来实现相等。如果有一个实现set的地方,你可以定义一个自定义相等函数,就像我使用的那个(或类似的)函数那么这将是一个很好的解决方案 – Hendrik

回答

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() 
+0

哦,这个等价类看起来非常有前途:) – Hendrik

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 
+0

尽管这应该在技术上起作用,但它违反了Comparator的合同,它暗示0如果两个对象相等则返回 –

-1

如果你不希望有手术后排序列表,复制或使用答案与Set(但Set [1,1,1] == [1])。

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; 
    } 
} 
相关问题