`

Java里面如何求两个集合的交集

    博客分类:
  • java
阅读更多
Java代码 :
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; 
    } 


    可以看到,先对两个不同的集合进行元素标记,并记下各自每个元素出现的次数,然后提取出两个集合中不重复的元素,
取两者中元素出现次数最少的数值,进行循环添加
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics