Here you can find the source of intersectionInplace(List
public static <X> Set<X> intersectionInplace(List<Set<X>> sets)
//package com.java2s; /*// w w w . j a v a 2 s . co m * This file is part of the Spider Web Framework. * * The Spider Web Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Spider Web Framework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Spider Web Framework. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; public class Main { private static Comparator<Collection<?>> sortBySizeReversed = new Comparator<Collection<?>>() { public int compare(Collection<?> o1, Collection<?> o2) { // swap o1 and o2 to reverse ordering return ((Integer) o2.size()).compareTo(o1.size()); } }; /** * @return intersection between all the sets * * The intersection is performed "inplace" using one of the sets. * The list of sets will also (possibly) be reordered. */ public static <X> Set<X> intersectionInplace(List<Set<X>> sets) { if (sets.isEmpty()) return Collections.emptySet(); if (sets.size() == 1) return sets.get(0); // sort collections so we can find the smallest and iterate from biggest to smallest Collections.sort(sets, sortBySizeReversed); // start with the last and smallest set Set<X> set = sets.remove(sets.size() - 1); // the idea is to try to make the intersection as small as possible // early in the iteration by starting with the biggest data set. // It's then most likely to remove the most items. return retainAllAll(set, sets); } private static <X> Set<X> retainAllAll(Set<X> set, Collection<Set<X>> sets) { // it's important that we're retaining with sets, because it will perform something like: // for item in sets: // set = [i for i in set if i in item] for (Set<X> item : sets) { set.retainAll(item); } return set; } }