Here you can find the source of intersection(final Collection
public static <T> Collection<T> intersection(final Collection<T> a, final Collection<T> b)
//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; } }