類別1:如何比較兩個集合並獲取它們之間的匹配數量?集合還包含重複
{ "tom", "dick", "harry", "john", "smith", "dick" };
系列2:
{ "Rachel", "dick", "tom", "dick", "smith","harry","Orion"}
的重複應計數兩次。
類別1:如何比較兩個集合並獲取它們之間的匹配數量?集合還包含重複
{ "tom", "dick", "harry", "john", "smith", "dick" };
系列2:
{ "Rachel", "dick", "tom", "dick", "smith","harry","Orion"}
的重複應計數兩次。
你可以只是做一個交集,並得到結果集的大小:
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.使用Collections.frequency()
方法來檢查特定字符串對象在集合中發生的次數。
2.現在,您可以在其他集合每個對象,如果任一對象的頻率數在另一個集合爲零,其明顯的是,這個集合不具有該對象的檢查頻率,所以這些集合是不相等的。
如果第一個集合中的所有對象都存在於第2話,嘗試檢查第2集的對象以相同的方式爲我點提到的2
[你嘗試過什麼? ](http://www.whathaveyoutried.com/) –
如何處理dup?數他們兩次?一旦? – elyashiv
它是什麼類型的集合,你可以請指定..字符串,IEnumerable,JSON等? –