Java tutorial
//package com.java2s; /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Main { @SuppressWarnings("unchecked") public static <T> Set<T> inter(final Set<T> a, final Set<T> b) { return (Set<T>) interSubtype(a, b); } public static <T> Set<T> inter(final Set<T>... sets) { return inter(Arrays.asList(sets)); } public static <T> Set<T> inter(final List<Set<T>> sets) { final List<Set<T>> mutable = new ArrayList<Set<T>>(sets.size()); for (final Set<T> s : sets) { // ignore nulls if (s != null) mutable.add(s); } if (mutable.isEmpty()) return null; else if (mutable.size() == 1) return mutable.get(0); final int indexMin = indexOfMinSize(mutable); if (indexMin != 0) { mutable.add(0, mutable.remove(indexMin)); return inter(mutable); } if (mutable.get(0).isEmpty()) return Collections.emptySet(); // replace the first 2 by their intersection // (inter will swap as appropriate if java doesn't evalute args in source order) mutable.add(0, inter(mutable.remove(0), mutable.remove(0))); return inter(mutable); } public static <T> Set<? extends T> interSubtype(final Set<? extends T> a, final Set<? extends T> b) { if (a == b) return a; else if (a == null) return b; else if (b == null) return a; else if (a.size() > b.size()) { return interSubtype(b, a); } final Set<T> res = new HashSet<T>(); for (final T item : a) { if (b.contains(item)) res.add(item); } return res; } private static final <T> int indexOfMinSize(final List<Set<T>> sets) { if (sets.isEmpty()) throw new IllegalArgumentException("empty sets"); int res = 0; for (int i = 1; i < sets.size(); i++) { if (sets.get(i).size() < sets.get(res).size()) res = i; } return res; } /** * Test whether col2 is contained in col1. * * @param <T> type of collection * @param col1 the first collection * @param col2 the second collection * @return <code>null</code> if col1 contains all of col2, else return the extra items that col2 * have. */ static public <T> Set<T> contains(final Set<T> col1, final Set<T> col2) { if (col1.containsAll(col2)) return null; else { final Set<T> names = new HashSet<T>(col2); names.removeAll(col1); return names; } } }