2012-09-19 34 views

回答

4

你可以只是做一個交集,並得到結果集的大小:

Set<String> s1 = new HashSet<String>(Arrays.asList(new String[] {"tom", "dick", "harry", "john", "smith", "dick"})); 
Set<String> s2 = new HashSet<String>(Arrays.asList(new String[] {"Rachel", "dick", "tom", "dick", "smith", "harry", "Orion"})); 

s1.retainAll(s2); // s1 becomes the intersection of s1 & s2 

System.out.println("Number of common elements: " + s1.size()); 

[編輯]應該有更多的仔細閱讀的問題。將上面的Set替換爲Apache Commons中的Bag實現,它也適用於重複項。

Set實現在retainAll調用後給出了s1的大小4,而Bag版本的大小爲5,我相信這是你想要的。

1

1.使用Collections.frequency()方法來檢查特定字符串對象在集合中發生的次數。

2.現在,您可以在其他集合每個對象,如果任一對象的頻率數在另一個集合爲零,其明顯的是,這個集合不具有該對象的檢查頻率,所以這些集合是不相等的。

如果第一個集合中的所有對象都存在於第2話,嘗試檢查第2集的對象以相同的方式爲我點提到的2