比较java Collection中的所有唯一对

时间:2012-01-22 02:17:42

标签: java

我有一个Collection<Pair<classA, Collection<classB>>>类型的集合。现在我想对集合中的每一个可能的对做一些事情,我不想重复对,即如果我已经比较[a,b],我不想comapre [b,a]。我想的一个解决方案是从集合中创建一个multimap,然后comapre所有唯一的对,但似乎我们不能在map中使用index vise元素,我的意思是像get(i)

for(int i = 0; i<map.size()-1; i++)
for(int j = i+1; j<map.size()-1; j++)
dosomething(multimap.getvalue(i), multimap.getValue(j));

请帮我解决这个问题。已经用了很多心思并做了很多搜索,但无法弄清楚。希望有些天才可以帮助我。

提前多多感谢!

1 个答案:

答案 0 :(得分:1)

我对这里的类型并不完全清楚,但我会创建一个名为UnorderedPair的类:

class UnorderedPair {
  Object a; // or whatever type should go here
  Object b;
  public int hashCode() { return a.hashCode() + b.hashCode(); }
  public boolean equals(Object o) { 
    if (o instanceof UnorderedPair) {
      UnorderedPair other = (UnorderedPair) o;
      return (a.equals(other.a) && b.equals(other.b))
          || (a.equals(other.b) && b.equals(other.a));
    }
    return false;
  }
}

然后你可以使用Set跟踪已经看过哪些对:

Set<UnorderedPair> seen = new HashSet<UnorderedPair>();
...look at a and b...
UnorderedPair p = new UnorderedPair(a, b); // or a factory would be nicer
if(seen.add(p)) {
  // this is a new pair
  doThingWith(a, b);
}
相关问题