在Python里,或许我们没有这个烦恼,因为python里已经为我们提供了intersection这样的方法。
但是在Java里,就需要我们动一番脑筋了。这里浓重推荐下apache的CollectionUtils工具类。
方法签名如下所示:
org.apache.commons.collections.intersection(final Collection a, final Collection b)
那么这个方法是怎么实现的呢?这里以list为例
public class TestIntersection {
private static final Integer ONE = new Integer(1); public static void main(String[] args) { // a集合[a,a,b,b,b,c] List<String> a = Arrays.asList("a", "a", "b", "b", "b", "c"); // b集合[a,b,b,c,c] List<String> b = Arrays.asList("a", "b", "b", "c", "c"); Map mapa = mapForCollection(a); Map mapb = mapForCollection(b); // 将两个集合里不重复的元素加进来,然后会依次遍历元素的出现次数 Set set = new HashSet(a); set.addAll(b); List<String> result = new ArrayList<String>(); for (Object obj : set) { for (int i = 0, m = Math.min(getCountsFromMap(obj, mapa), getCountsFromMap(obj, mapb)); i < m; i++) { result.add((String) obj); } } // 看下期待的结果是不是[a,b,b,c] System.out.println(result); } /** * 循环遍历集合,并对每一个元素出现的次数计数<br/> * 最终返回类似于{A:1,B:3,C:3}这样的map * * @param a * @return */ private static Map mapForCollection(Collection a) { Map map = new HashMap(); Iterator it = a.iterator(); while (it.hasNext()) { Object obj = it.next(); Integer count = (Integer) map.get(obj); if (count == null) { // 表明该元素第一次出现 map.put(obj, ONE); } else { map.put(obj, new Integer(count.intValue() + 1)); } } return map; } private static int getCountsFromMap(Object obj, Map map) { Integer count = (Integer) map.get(obj); return count != null ? count.intValue() : 0; } }
可以看到,先对两个不同的集合进行元素标记,并记下各自每个元素出现的次数,然后提取出两个集合中不重复的元素,
取两者中元素出现次数最少的数值,进行循环添加