Java Collection Intersect intersection(final Collection a, final Collection b)

Here you can find the source of intersection(final Collection a, final Collection b)

Description

intersection

License

Open Source License

Declaration

@SuppressWarnings({ "rawtypes", "unchecked" })
    public static Collection intersection(final Collection a, final Collection b) 

Method Source Code

//package com.java2s;
/**//ww w .  j  a v  a2 s  . c o m
 * License: src/main/resources/license/escidoc.license
 */

import java.util.ArrayList;
import java.util.Collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;

import java.util.Map;
import java.util.Set;

public class Main {
    private static Integer INTEGER_ONE = new Integer(1);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Collection intersection(final Collection a, final Collection b) {
        ArrayList list = new ArrayList();
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Set elts = new LinkedHashSet(a);
        elts.addAll(b);
        Iterator it = elts.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            for (int i = 0, m = Math.min(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) {
                list.add(obj);
            }
        }
        return list;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map getCardinalityMap(final Collection coll) {
        Map count = new HashMap();
        for (Iterator it = coll.iterator(); it.hasNext();) {
            Object obj = it.next();
            Integer c = (Integer) (count.get(obj));
            if (c == null) {
                count.put(obj, INTEGER_ONE);
            } else {
                count.put(obj, new Integer(c.intValue() + 1));
            }
        }
        return count;
    }

    @SuppressWarnings({ "rawtypes" })
    private static final int getFreq(final Object obj, final Map freqMap) {
        Integer count = (Integer) freqMap.get(obj);
        if (count != null) {
            return count.intValue();
        }
        return 0;
    }
}

Related

  1. intersection(Collection> sets)
  2. intersection(Collection a, Collection b)
  3. intersection(Collection a, Collection b)
  4. intersection(Collection a, Collection b)
  5. intersection(Collection values1, Collection values2)
  6. intersection(final Collection c1, final Collection c2)
  7. intersection(final Collection a, final Collection b)
  8. intersection(final Collection c1, final Collection c2)
  9. intersectionSize(Collection c1, Collection c2)