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

public static <T> Collection<T> intersection(final Collection<T> a, final Collection<T> b) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

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

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

    public static <T> Collection<T> intersection(final Collection<T> a, final Collection<T> b) {
        if (a == null || a.size() == 0 || b == null || b.size() == 0) {
            return null;
        }/*from w w  w .  j a  v a  2 s.  c o  m*/

        List<T> result = new ArrayList<T>();
        Map<T, Integer> mapa = getCardinalityMap(a);
        Map<T, Integer> mapb = getCardinalityMap(b);

        Set<T> elts = new HashSet<T>(a);
        elts.addAll(b);
        Iterator<T> it = elts.iterator();
        while (it.hasNext()) {
            T t = it.next();
            for (int i = 0, m = Math.min(getFreq(t, mapa), getFreq(t, mapb)); i < m; i++) {
                result.add(t);
            }
        }
        return result;
    }

    public static <T> Map<T, Integer> getCardinalityMap(final Collection<T> coll) {
        if (coll == null) {
            return null;
        }

        Map<T, Integer> result = new HashMap<T, Integer>();
        Iterator<T> it = coll.iterator();
        while (it.hasNext()) {
            T t = it.next();
            Integer count = result.get(t);
            if (count == null) {
                result.put(t, ONE);
            } else {
                result.put(t, new Integer(count.intValue() + 1));
            }
        }
        return result;
    }

    private static final <T> int getFreq(final T obj, final Map<T, Integer> freqMap) {
        Integer count = freqMap.get(obj);
        if (count != null) {
            return count.intValue();
        }
        return 0;
    }
}

Related

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