Java tutorial
//package com.java2s; /* * Copyright The Codehaus Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; public class Main { /** * Returns a {@link Collection} containing the intersection * of the given {@link Collection}s. * <p> * The cardinality of each element in the returned {@link Collection} * will be equal to the minimum of the cardinality of that element * in the two given {@link Collection}s. * * @param a The first collection * @param b The second collection * @see Collection#retainAll * @return The intersection of a and b, never null */ public static <E> Collection<E> intersection(final Collection<E> a, final Collection<E> b) { ArrayList<E> list = new ArrayList<E>(); Map<E, Integer> mapa = getCardinalityMap(a); Map<E, Integer> mapb = getCardinalityMap(b); Set<E> elts = new HashSet<E>(a); elts.addAll(b); for (E obj : elts) { for (int i = 0, m = Math.min(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) { list.add(obj); } } return list; } /** * Returns a {@link Map} mapping each unique element in * the given {@link Collection} to an {@link Integer} * representing the number of occurances of that element * in the {@link Collection}. * An entry that maps to <tt>null</tt> indicates that the * element does not appear in the given {@link Collection}. * @param col The collection to count cardinalities for * @return A map of counts, indexed on each element in the collection */ public static <E> Map<E, Integer> getCardinalityMap(final Collection<E> col) { HashMap<E, Integer> count = new HashMap<E, Integer>(); for (E obj : col) { Integer c = count.get(obj); if (null == c) { count.put(obj, 1); } else { count.put(obj, c + 1); } } return count; } private static <E> int getFreq(final E obj, final Map<E, Integer> freqMap) { try { Integer o = freqMap.get(obj); if (o != null) // minimize NullPointerExceptions { return o; } } catch (NullPointerException ignore) { } catch (NoSuchElementException ignore) { } return 0; } }