2012-01-22 9 views
2

我有一個集合Collection<Pair<classA, Collection<classB>>>。現在我想對集合中的每一對可能的東西做一些事情,我不想重複對,即如果我比較了[a,b],我不想comapre [b,a]。一個解決方案,我想是使從集合多重映射,然後comapre所有唯一對,但似乎我們不能在地圖中使用索引老虎鉗元素也,我的意思是這樣的get(我)比較java集合中的所有唯一對

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)); 

請幫我在解決這個問題。用了很多心思,做了很多搜索,但無法弄清楚。希望有些天才能幫助我。

非常感謝!

+0

等等。 A和B是同一種類型嗎? –

回答

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); 
}