-3

收藏一:

{ "tom", "dick", "harry", "john", "smith", "dick" };

收藏2:

{ "Rachel", "dick", "tom", "dick", "smith","harry","Orion"}

重复项应计算两次。

4

2 回答 2

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后为 s1 提供了 4 的大小,而版本的大小为 5,我相信这是您想要的。retainAllBag

于 2012-09-19T05:19:45.953 回答
1

1.使用Collections.frequency()方法检查特定String对象在Collection中出现的次数。

2.现在你可以检查每个Object在另一个Collection中的频率,如果任何一个Object在另一个Collection中的频率计数为零,很明显这个Collection没有那个对象,所以这些Collection不相等。

3.如果第一个集合的所有对象都存在于第二个集合中,请尝试按照我在第 2 点中提到的相同方式检查第二个集合的对象。

于 2012-09-19T05:22:32.300 回答