CollectionUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.collections4;

  18. import java.lang.reflect.Array;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.Comparator;
  23. import java.util.Enumeration;
  24. import java.util.HashMap;
  25. import java.util.HashSet;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.ListIterator;
  29. import java.util.Map;
  30. import java.util.Objects;
  31. import java.util.Set;

  32. import org.apache.commons.collections4.bag.HashBag;
  33. import org.apache.commons.collections4.collection.PredicatedCollection;
  34. import org.apache.commons.collections4.collection.SynchronizedCollection;
  35. import org.apache.commons.collections4.collection.TransformedCollection;
  36. import org.apache.commons.collections4.collection.UnmodifiableBoundedCollection;
  37. import org.apache.commons.collections4.collection.UnmodifiableCollection;
  38. import org.apache.commons.collections4.functors.TruePredicate;
  39. import org.apache.commons.collections4.iterators.CollatingIterator;
  40. import org.apache.commons.collections4.iterators.PermutationIterator;

  41. /**
  42.  * Provides utility methods and decorators for {@link Collection} instances.
  43.  * <p>
  44.  * Various utility methods might put the input objects into a Set/Map/Bag. In case
  45.  * the input objects override {@link Object#equals(Object)}, it is mandatory that
  46.  * the general contract of the {@link Object#hashCode()} method is maintained.
  47.  * </p>
  48.  * <p>
  49.  * NOTE: From 4.0, method parameters will take {@link Iterable} objects when possible.
  50.  * </p>
  51.  *
  52.  * @since 1.0
  53.  */
  54. public class CollectionUtils {

  55.     /**
  56.      * Helper class to easily access cardinality properties of two collections.
  57.      * @param <O>  the element type
  58.      */
  59.     private static class CardinalityHelper<O> {

  60.         static boolean equals(final Collection<?> a, final Collection<?> b) {
  61.             return new HashBag<>(a).equals(new HashBag<>(b));
  62.         }

  63.         /** Contains the cardinality for each object in collection A. */
  64.         final Bag<O> cardinalityA;

  65.         /** Contains the cardinality for each object in collection B. */
  66.         final Bag<O> cardinalityB;

  67.         /**
  68.          * Creates a new CardinalityHelper for two collections.
  69.          *
  70.          * @param a  the first collection
  71.          * @param b  the second collection
  72.          */
  73.         CardinalityHelper(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  74.             cardinalityA = new HashBag<>(a);
  75.             cardinalityB = new HashBag<>(b);
  76.         }

  77.         /**
  78.          * Gets the frequency of this object in collection A.
  79.          *
  80.          * @param key the key whose associated frequency is to be returned.
  81.          * @return the frequency of the object in collection A
  82.          */
  83.         public int freqA(final Object key) {
  84.             return getFreq(key, cardinalityA);
  85.         }

  86.         /**
  87.          * Gets the frequency of this object in collection B.
  88.          *
  89.          * @param key the key whose associated frequency is to be returned.
  90.          * @return the frequency of the object in collection B
  91.          */
  92.         public int freqB(final Object key) {
  93.             return getFreq(key, cardinalityB);
  94.         }

  95.         private int getFreq(final Object key, final Bag<?> freqMap) {
  96.             return freqMap.getCount(key);
  97.         }

  98.         /**
  99.          * Gets the maximum frequency of an object.
  100.          *
  101.          * @param obj  the object
  102.          * @return the maximum frequency of the object
  103.          */
  104.         public final int max(final Object obj) {
  105.             return Math.max(freqA(obj), freqB(obj));
  106.         }

  107.         /**
  108.          * Gets the minimum frequency of an object.
  109.          *
  110.          * @param obj  the object
  111.          * @return the minimum frequency of the object
  112.          */
  113.         public final int min(final Object obj) {
  114.             return Math.min(freqA(obj), freqB(obj));
  115.         }
  116.     }

  117.     /**
  118.      * Wraps another object and uses the provided Equator to implement
  119.      * {@link #equals(Object)} and {@link #hashCode()}.
  120.      * <p>
  121.      * This class can be used to store objects into a Map.
  122.      * </p>
  123.      *
  124.      * @param <O>  the element type
  125.      * @since 4.0
  126.      */
  127.     private static final class EquatorWrapper<O> {
  128.         private final Equator<? super O> equator;
  129.         private final O object;

  130.         EquatorWrapper(final Equator<? super O> equator, final O object) {
  131.             this.equator = equator;
  132.             this.object = object;
  133.         }

  134.         @Override
  135.         public boolean equals(final Object obj) {
  136.             if (!(obj instanceof EquatorWrapper)) {
  137.                 return false;
  138.             }
  139.             @SuppressWarnings("unchecked")
  140.             final EquatorWrapper<O> otherObj = (EquatorWrapper<O>) obj;
  141.             return equator.equate(object, otherObj.getObject());
  142.         }

  143.         public O getObject() {
  144.             return object;
  145.         }

  146.         @Override
  147.         public int hashCode() {
  148.             return equator.hash(object);
  149.         }
  150.     }

  151.     /**
  152.      * Helper class for set-related operations, for example union, subtract, intersection.
  153.      * @param <O>  the element type
  154.      */
  155.     private static final class SetOperationCardinalityHelper<O> extends CardinalityHelper<O> implements Iterable<O> {

  156.         /** Contains the unique elements of the two collections. */
  157.         private final Set<O> elements;

  158.         /** Output collection. */
  159.         private final List<O> newList;

  160.         /**
  161.          * Create a new set operation helper from the two collections.
  162.          * @param a  the first collection
  163.          * @param b  the second collection
  164.          */
  165.         SetOperationCardinalityHelper(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  166.             super(a, b);
  167.             elements = new HashSet<>();
  168.             addAll(elements, a);
  169.             addAll(elements, b);
  170.             // the resulting list must contain at least each unique element, but may grow
  171.             newList = new ArrayList<>(elements.size());
  172.         }

  173.         @Override
  174.         public Iterator<O> iterator() {
  175.             return elements.iterator();
  176.         }

  177.         /**
  178.          * Returns the resulting collection.
  179.          * @return the result
  180.          */
  181.         public Collection<O> list() {
  182.             return newList;
  183.         }

  184.         /**
  185.          * Add the object {@code count} times to the result collection.
  186.          * @param obj  the object to add
  187.          * @param count  the count
  188.          */
  189.         public void setCardinality(final O obj, final int count) {
  190.             for (int i = 0; i < count; i++) {
  191.                 newList.add(obj);
  192.             }
  193.         }

  194.     }

  195.     /**
  196.      * The index value when an element is not found in a collection or array: {@code -1}.
  197.      *
  198.      * @since 4.5.0-M1
  199.      */
  200.     public static final int INDEX_NOT_FOUND = -1;

  201.     /**
  202.      * Default prefix used while converting an Iterator to its String representation.
  203.      *
  204.      * @since 4.5.0-M1
  205.      */
  206.     public static final String DEFAULT_TOSTRING_PREFIX = "[";

  207.     /**
  208.      * Default suffix used while converting an Iterator to its String representation.
  209.      *
  210.      * @since 4.5.0-M1
  211.      */
  212.     public static final String DEFAULT_TOSTRING_SUFFIX = "]";

  213.     /**
  214.      * A String for Colon  (":").
  215.      *
  216.      * @since 4.5.0-M1
  217.      */
  218.     public static final String COLON = ":";

  219.     /**
  220.      * A String for Comma (",").
  221.      *
  222.      * @since 4.5.0-M1
  223.      */
  224.     public static final String COMMA = ",";

  225.     /**
  226.      * An empty unmodifiable collection.
  227.      * The JDK provides empty Set and List implementations which could be used for
  228.      * this purpose. However they could be cast to Set or List which might be
  229.      * undesirable. This implementation only implements Collection.
  230.      */
  231.     @SuppressWarnings("rawtypes") // we deliberately use the raw type here
  232.     public static final Collection EMPTY_COLLECTION = Collections.emptyList();

  233.     /**
  234.      * Adds all elements in the array to the given collection.
  235.      *
  236.      * @param <C>  the type of object the {@link Collection} contains
  237.      * @param collection  the collection to add to, must not be null
  238.      * @param elements  the array of elements to add, must not be null
  239.      * @return {@code true} if the collection was changed, {@code false} otherwise
  240.      * @throws NullPointerException if the collection or elements is null
  241.      */
  242.     public static <C> boolean addAll(final Collection<C> collection, final C... elements) {
  243.         Objects.requireNonNull(collection, "collection");
  244.         Objects.requireNonNull(elements, "elements");
  245.         boolean changed = false;
  246.         for (final C element : elements) {
  247.             changed |= collection.add(element);
  248.         }
  249.         return changed;
  250.     }

  251.     /**
  252.      * Adds all elements in the enumeration to the given collection.
  253.      *
  254.      * @param <C>  the type of object the {@link Collection} contains
  255.      * @param collection  the collection to add to, must not be null
  256.      * @param enumeration  the enumeration of elements to add, must not be null
  257.      * @return {@code true} if the collections was changed, {@code false} otherwise
  258.      * @throws NullPointerException if the collection or enumeration is null
  259.      */
  260.     public static <C> boolean addAll(final Collection<C> collection, final Enumeration<? extends C> enumeration) {
  261.         Objects.requireNonNull(collection, "collection");
  262.         Objects.requireNonNull(enumeration, "enumeration");
  263.         boolean changed = false;
  264.         while (enumeration.hasMoreElements()) {
  265.             changed |= collection.add(enumeration.nextElement());
  266.         }
  267.         return changed;
  268.     }

  269.     /**
  270.      * Adds all elements in the {@link Iterable} to the given collection. If the
  271.      * {@link Iterable} is a {@link Collection} then it is cast and will be
  272.      * added using {@link Collection#addAll(Collection)} instead of iterating.
  273.      *
  274.      * @param <C>  the type of object the {@link Collection} contains
  275.      * @param collection  the collection to add to, must not be null
  276.      * @param iterable  the iterable of elements to add, must not be null
  277.      * @return a boolean indicating whether the collection has changed or not.
  278.      * @throws NullPointerException if the collection or iterable is null
  279.      */
  280.     public static <C> boolean addAll(final Collection<C> collection, final Iterable<? extends C> iterable) {
  281.         Objects.requireNonNull(collection, "collection");
  282.         Objects.requireNonNull(iterable, "iterable");
  283.         if (iterable instanceof Collection<?>) {
  284.             return collection.addAll((Collection<? extends C>) iterable);
  285.         }
  286.         return addAll(collection, iterable.iterator());
  287.     }

  288.     /**
  289.      * Adds all elements in the iteration to the given collection.
  290.      *
  291.      * @param <C>  the type of object the {@link Collection} contains
  292.      * @param collection  the collection to add to, must not be null
  293.      * @param iterator  the iterator of elements to add, must not be null
  294.      * @return a boolean indicating whether the collection has changed or not.
  295.      * @throws NullPointerException if the collection or iterator is null
  296.      */
  297.     public static <C> boolean addAll(final Collection<C> collection, final Iterator<? extends C> iterator) {
  298.         Objects.requireNonNull(collection, "collection");
  299.         Objects.requireNonNull(iterator, "iterator");
  300.         boolean changed = false;
  301.         while (iterator.hasNext()) {
  302.             changed |= collection.add(iterator.next());
  303.         }
  304.         return changed;
  305.     }

  306.     /**
  307.      * Adds an element to the collection unless the element is null.
  308.      *
  309.      * @param <T>  the type of object the {@link Collection} contains
  310.      * @param collection  the collection to add to, must not be null
  311.      * @param object  the object to add, if null it will not be added
  312.      * @return true if the collection changed
  313.      * @throws NullPointerException if the collection is null
  314.      * @since 3.2
  315.      */
  316.     public static <T> boolean addIgnoreNull(final Collection<T> collection, final T object) {
  317.         Objects.requireNonNull(collection, "collection");
  318.         return object != null && collection.add(object);
  319.     }

  320.     /**
  321.      * Returns the number of occurrences of <em>obj</em> in <em>coll</em>.
  322.      *
  323.      * @param obj the object to find the cardinality of
  324.      * @param collection the {@link Iterable} to search
  325.      * @param <O> the type of object that the {@link Iterable} may contain.
  326.      * @return the number of occurrences of obj in coll
  327.      * @throws NullPointerException if collection is null
  328.      * @deprecated since 4.1, use {@link IterableUtils#frequency(Iterable, Object)} instead.
  329.      *   Be aware that the order of parameters has changed.
  330.      */
  331.     @Deprecated
  332.     public static <O> int cardinality(final O obj, final Iterable<? super O> collection) {
  333.         return IterableUtils.frequency(Objects.requireNonNull(collection, "collection"), obj);
  334.     }

  335.     /**
  336.      * Ensures an index is not negative.
  337.      * @param index the index to check.
  338.      * @throws IndexOutOfBoundsException if the index is negative.
  339.      */
  340.     static void checkIndexBounds(final int index) {
  341.         if (index < 0) {
  342.             throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
  343.         }
  344.     }

  345.     /**
  346.      * Merges two sorted Collections, a and b, into a single, sorted List
  347.      * such that the natural ordering of the elements is retained.
  348.      * <p>
  349.      * Uses the standard O(n) merge algorithm for combining two sorted lists.
  350.      * </p>
  351.      *
  352.      * @param <O>  the element type
  353.      * @param a  the first collection, must not be null
  354.      * @param b  the second collection, must not be null
  355.      * @return a new sorted List, containing the elements of Collection a and b
  356.      * @throws NullPointerException if either collection is null
  357.      * @since 4.0
  358.      */
  359.     public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
  360.                                                                     final Iterable<? extends O> b) {
  361.         return collate(a, b, ComparatorUtils.<O>naturalComparator(), true);
  362.     }

  363.     /**
  364.      * Merges two sorted Collections, a and b, into a single, sorted List
  365.      * such that the natural ordering of the elements is retained.
  366.      * <p>
  367.      * Uses the standard O(n) merge algorithm for combining two sorted lists.
  368.      * </p>
  369.      *
  370.      * @param <O>  the element type
  371.      * @param a  the first collection, must not be null
  372.      * @param b  the second collection, must not be null
  373.      * @param includeDuplicates  if {@code true} duplicate elements will be retained, otherwise
  374.      *   they will be removed in the output collection
  375.      * @return a new sorted List, containing the elements of Collection a and b
  376.      * @throws NullPointerException if either collection is null
  377.      * @since 4.0
  378.      */
  379.     public static <O extends Comparable<? super O>> List<O> collate(final Iterable<? extends O> a,
  380.                                                                     final Iterable<? extends O> b,
  381.                                                                     final boolean includeDuplicates) {
  382.         return collate(a, b, ComparatorUtils.<O>naturalComparator(), includeDuplicates);
  383.     }

  384.     /**
  385.      * Merges two sorted Collections, a and b, into a single, sorted List
  386.      * such that the ordering of the elements according to Comparator c is retained.
  387.      * <p>
  388.      * Uses the standard O(n) merge algorithm for combining two sorted lists.
  389.      * </p>
  390.      *
  391.      * @param <O>  the element type
  392.      * @param a  the first collection, must not be null
  393.      * @param b  the second collection, must not be null
  394.      * @param c  the comparator to use for the merge.
  395.      * @return a new sorted List, containing the elements of Collection a and b
  396.      * @throws NullPointerException if either collection or the comparator is null
  397.      * @since 4.0
  398.      */
  399.     public static <O> List<O> collate(final Iterable<? extends O> a, final Iterable<? extends O> b,
  400.                                       final Comparator<? super O> c) {
  401.         return collate(a, b, c, true);
  402.     }

  403.     /**
  404.      * Merges two sorted Collections, a and b, into a single, sorted List
  405.      * such that the ordering of the elements according to Comparator c is retained.
  406.      * <p>
  407.      * Uses the standard O(n) merge algorithm for combining two sorted lists.
  408.      * </p>
  409.      *
  410.      * @param <O>  the element type
  411.      * @param iterableA  the first collection, must not be null
  412.      * @param iterableB  the second collection, must not be null
  413.      * @param comparator  the comparator to use for the merge.
  414.      * @param includeDuplicates  if {@code true} duplicate elements will be retained, otherwise
  415.      *   they will be removed in the output collection
  416.      * @return a new sorted List, containing the elements of Collection a and b
  417.      * @throws NullPointerException if either collection or the comparator is null
  418.      * @since 4.0
  419.      */
  420.     public static <O> List<O> collate(final Iterable<? extends O> iterableA, final Iterable<? extends O> iterableB,
  421.                                       final Comparator<? super O> comparator, final boolean includeDuplicates) {
  422.         Objects.requireNonNull(iterableA, "iterableA");
  423.         Objects.requireNonNull(iterableB, "iterableB");
  424.         Objects.requireNonNull(comparator, "comparator");
  425.         // if both Iterables are a Collection, we can estimate the size
  426.         final int totalSize = iterableA instanceof Collection<?> && iterableB instanceof Collection<?> ?
  427.                 Math.max(1, ((Collection<?>) iterableA).size() + ((Collection<?>) iterableB).size()) : 10;

  428.         final Iterator<O> iterator = new CollatingIterator<>(comparator, iterableA.iterator(), iterableB.iterator());
  429.         if (includeDuplicates) {
  430.             return IteratorUtils.toList(iterator, totalSize);
  431.         }
  432.         final ArrayList<O> mergedList = new ArrayList<>(totalSize);
  433.         O lastItem = null;
  434.         while (iterator.hasNext()) {
  435.             final O item = iterator.next();
  436.             if (lastItem == null || !lastItem.equals(item)) {
  437.                 mergedList.add(item);
  438.             }
  439.             lastItem = item;
  440.         }
  441.         mergedList.trimToSize();
  442.         return mergedList;
  443.     }

  444.     /**
  445.      * Transforms all elements from input collection with the given transformer
  446.      * and adds them to the output collection.
  447.      * <p>
  448.      * If the input collection or transformer is null, there is no change to the
  449.      * output collection.
  450.      * </p>
  451.      *
  452.      * @param <I>  the type of object in the input collection
  453.      * @param <O>  the type of object in the output collection
  454.      * @param <R>  the type of the output collection
  455.      * @param inputCollection  the collection to get the input from, may be null
  456.      * @param transformer  the transformer to use, may be null
  457.      * @param outputCollection  the collection to output into, may not be null if inputCollection
  458.      *   and transformer are not null
  459.      * @return the output collection with the transformed input added
  460.      * @throws NullPointerException if the outputCollection is null and both, inputCollection and
  461.      *   transformer are not null
  462.      */
  463.     public static <I, O, R extends Collection<? super O>> R collect(final Iterable<? extends I> inputCollection,
  464.             final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
  465.         if (inputCollection != null) {
  466.             return collect(inputCollection.iterator(), transformer, outputCollection);
  467.         }
  468.         return outputCollection;
  469.     }

  470.     /**
  471.      * Returns a new Collection containing all elements of the input collection
  472.      * transformed by the given transformer.
  473.      * <p>
  474.      * If the input collection or transformer is null, the result is an empty list.
  475.      * </p>
  476.      *
  477.      * @param <I>  the type of object in the input collection
  478.      * @param <O>  the type of object in the output collection
  479.      * @param inputCollection  the collection to get the input from, may not be null
  480.      * @param transformer  the transformer to use, may be null
  481.      * @return the transformed result (new list)
  482.      * @throws NullPointerException if the outputCollection is null and both, inputCollection and
  483.      *   transformer are not null
  484.      */
  485.     public static <I, O> Collection<O> collect(final Iterable<I> inputCollection,
  486.                                                final Transformer<? super I, ? extends O> transformer) {
  487.         int size = 0;
  488.         if (null != inputCollection) {
  489.             size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
  490.         }
  491.         final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
  492.         return collect(inputCollection, transformer, answer);
  493.     }

  494.     /**
  495.      * Transforms all elements from the input iterator with the given transformer
  496.      * and adds them to the output collection.
  497.      * <p>
  498.      * If the input iterator or transformer is null, there is no change to the
  499.      * output collection.
  500.      * </p>
  501.      *
  502.      * @param <I>  the type of object in the input collection
  503.      * @param <O>  the type of object in the output collection
  504.      * @param <R>  the type of the output collection
  505.      * @param inputIterator  the iterator to get the input from, may be null
  506.      * @param transformer  the transformer to use, may be null
  507.      * @param outputCollection  the collection to output into, may not be null if inputIterator
  508.      *   and transformer are not null
  509.      * @return the outputCollection with the transformed input added
  510.      * @throws NullPointerException if the output collection is null and both, inputIterator and
  511.      *   transformer are not null
  512.      */
  513.     public static <I, O, R extends Collection<? super O>> R collect(final Iterator<? extends I> inputIterator,
  514.             final Transformer<? super I, ? extends O> transformer, final R outputCollection) {
  515.         if (inputIterator != null && transformer != null) {
  516.             while (inputIterator.hasNext()) {
  517.                 final I item = inputIterator.next();
  518.                 final O value = transformer.apply(item);
  519.                 outputCollection.add(value);
  520.             }
  521.         }
  522.         return outputCollection;
  523.     }

  524.     /**
  525.      * Transforms all elements from the input iterator with the given transformer
  526.      * and adds them to the output collection.
  527.      * <p>
  528.      * If the input iterator or transformer is null, the result is an empty list.
  529.      * </p>
  530.      *
  531.      * @param <I>  the type of object in the input collection
  532.      * @param <O>  the type of object in the output collection
  533.      * @param inputIterator  the iterator to get the input from, may be null
  534.      * @param transformer  the transformer to use, may be null
  535.      * @return the transformed result (new list)
  536.      */
  537.     public static <I, O> Collection<O> collect(final Iterator<I> inputIterator,
  538.                                                final Transformer<? super I, ? extends O> transformer) {
  539.         return collect(inputIterator, transformer, new ArrayList<>());
  540.     }

  541.     /**
  542.      * Returns {@code true} iff all elements of {@code coll2} are also contained
  543.      * in {@code coll1}. The cardinality of values in {@code coll2} is not taken into account,
  544.      * which is the same behavior as {@link Collection#containsAll(Collection)}.
  545.      * <p>
  546.      * In other words, this method returns {@code true} iff the
  547.      * {@link #intersection} of <em>coll1</em> and <em>coll2</em> has the same cardinality as
  548.      * the set of unique values from {@code coll2}. In case {@code coll2} is empty, {@code true}
  549.      * will be returned.
  550.      * </p>
  551.      * <p>
  552.      * This method is intended as a replacement for {@link Collection#containsAll(Collection)}
  553.      * with a guaranteed runtime complexity of {@code O(n + m)}. Depending on the type of
  554.      * {@link Collection} provided, this method will be much faster than calling
  555.      * {@link Collection#containsAll(Collection)} instead, though this will come at the
  556.      * cost of an additional space complexity O(n).
  557.      * </p>
  558.      *
  559.      * @param coll1  the first collection, must not be null
  560.      * @param coll2  the second collection, must not be null
  561.      * @return {@code true} iff the intersection of the collections has the same cardinality
  562.      *   as the set of unique elements from the second collection
  563.      * @throws NullPointerException if coll1 or coll2 is null
  564.      * @since 4.0
  565.      */
  566.     public static boolean containsAll(final Collection<?> coll1, final Collection<?> coll2) {
  567.         Objects.requireNonNull(coll1, "coll1");
  568.         Objects.requireNonNull(coll2, "coll2");
  569.         if (coll2.isEmpty()) {
  570.             return true;
  571.         }
  572.         final Set<Object> elementsAlreadySeen = new HashSet<>();
  573.         for (final Object nextElement : coll2) {
  574.             if (elementsAlreadySeen.contains(nextElement)) {
  575.                 continue;
  576.             }

  577.             boolean foundCurrentElement = false;
  578.             for (final Object p : coll1) {
  579.                 elementsAlreadySeen.add(p);
  580.                 if (Objects.equals(nextElement, p)) {
  581.                     foundCurrentElement = true;
  582.                     break;
  583.                 }
  584.             }

  585.             if (!foundCurrentElement) {
  586.                 return false;
  587.             }
  588.         }
  589.         return true;
  590.     }

  591.     /**
  592.      * Returns {@code true} iff at least one element is in both collections.
  593.      * <p>
  594.      * In other words, this method returns {@code true} iff the
  595.      * {@link #intersection} of <em>coll1</em> and <em>coll2</em> is not empty.
  596.      * </p>
  597.      *
  598.      * @param coll1  the first collection, must not be null
  599.      * @param coll2  the second collection, must not be null
  600.      * @return {@code true} iff the intersection of the collections is non-empty
  601.      * @throws NullPointerException if coll1 or coll2 is null
  602.      * @since 2.1
  603.      * @see #intersection
  604.      */
  605.     public static boolean containsAny(final Collection<?> coll1, final Collection<?> coll2) {
  606.         Objects.requireNonNull(coll1, "coll1");
  607.         Objects.requireNonNull(coll2, "coll2");
  608.         if (coll1.size() < coll2.size()) {
  609.             for (final Object aColl1 : coll1) {
  610.                 if (coll2.contains(aColl1)) {
  611.                     return true;
  612.                 }
  613.             }
  614.         } else {
  615.             for (final Object aColl2 : coll2) {
  616.                 if (coll1.contains(aColl2)) {
  617.                     return true;
  618.                 }
  619.             }
  620.         }
  621.         return false;
  622.     }

  623.     /**
  624.      * Returns {@code true} iff at least one element is in both collections.
  625.      * <p>
  626.      * In other words, this method returns {@code true} iff the
  627.      * {@link #intersection} of <em>coll1</em> and <em>coll2</em> is not empty.
  628.      * </p>
  629.      *
  630.      * @param <T> the type of object to lookup in {@code coll1}.
  631.      * @param coll1  the first collection, must not be {@code null}.
  632.      * @param coll2  the second collection, must not be {@code null}.
  633.      * @return {@code true} iff the intersection of the collections is non-empty.
  634.      * @throws NullPointerException if coll1 or coll2 is {@code null}.
  635.      * @since 4.2
  636.      * @see #intersection
  637.      */
  638.     public static <T> boolean containsAny(final Collection<?> coll1, @SuppressWarnings("unchecked") final T... coll2) {
  639.         Objects.requireNonNull(coll1, "coll1");
  640.         Objects.requireNonNull(coll2, "coll2");
  641.         if (coll1.size() < coll2.length) {
  642.             for (final Object aColl1 : coll1) {
  643.                 if (ArrayUtils.contains(coll2, aColl1)) {
  644.                     return true;
  645.                 }
  646.             }
  647.         } else {
  648.             for (final Object aColl2 : coll2) {
  649.                 if (coll1.contains(aColl2)) {
  650.                     return true;
  651.                 }
  652.             }
  653.         }
  654.         return false;
  655.     }

  656.     /**
  657.      * Counts the number of elements in the input collection that match the
  658.      * predicate.
  659.      * <p>
  660.      * A {@code null} collection or predicate matches no elements.
  661.      * </p>
  662.      *
  663.      * @param <C>  the type of object the {@link Iterable} contains
  664.      * @param input  the {@link Iterable} to get the input from, may be null
  665.      * @param predicate  the predicate to use, may be null
  666.      * @return the number of matches for the predicate in the collection
  667.      * @deprecated since 4.1, use {@link IterableUtils#countMatches(Iterable, Predicate)} instead
  668.      */
  669.     @Deprecated
  670.     public static <C> int countMatches(final Iterable<C> input, final Predicate<? super C> predicate) {
  671.         return predicate == null ? 0 : (int) IterableUtils.countMatches(input, predicate);
  672.     }

  673.     /**
  674.      * Returns a {@link Collection} containing the exclusive disjunction
  675.      * (symmetric difference) of the given {@link Iterable}s.
  676.      * <p>
  677.      * The cardinality of each element <em>e</em> in the returned
  678.      * {@link Collection} will be equal to
  679.      * <code>max(cardinality(<em>e</em>,<em>a</em>),cardinality(<em>e</em>,<em>b</em>)) - min(cardinality(<em>e</em>,<em>a</em>),
  680.      * cardinality(<em>e</em>,<em>b</em>))</code>.
  681.      * </p>
  682.      * <p>
  683.      * This is equivalent to
  684.      * {@code {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})}
  685.      * or
  686.      * {@code {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)})}.
  687.      * </p>
  688.      *
  689.      * @param a the first collection, must not be null
  690.      * @param b the second collection, must not be null
  691.      * @param <O> the generic type that is able to represent the types contained
  692.      *        in both input collections.
  693.      * @return the symmetric difference of the two collections
  694.      * @throws NullPointerException if either collection is null
  695.      */
  696.     public static <O> Collection<O> disjunction(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  697.         Objects.requireNonNull(a, "a");
  698.         Objects.requireNonNull(b, "b");
  699.         final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
  700.         for (final O obj : helper) {
  701.             helper.setCardinality(obj, helper.max(obj) - helper.min(obj));
  702.         }
  703.         return helper.list();
  704.     }

  705.     /**
  706.      * Returns the immutable EMPTY_COLLECTION with generic type safety.
  707.      *
  708.      * @see #EMPTY_COLLECTION
  709.      * @param <T> the element type
  710.      * @return immutable empty collection
  711.      * @since 4.0
  712.      */
  713.     @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type
  714.     public static <T> Collection<T> emptyCollection() {
  715.         return EMPTY_COLLECTION;
  716.     }

  717.     /**
  718.      * Returns an immutable empty collection if the argument is {@code null},
  719.      * or the argument itself otherwise.
  720.      *
  721.      * @param <T> the element type
  722.      * @param collection the collection, possibly {@code null}
  723.      * @return an empty collection if the argument is {@code null}
  724.      */
  725.     public static <T> Collection<T> emptyIfNull(final Collection<T> collection) {
  726.         return collection == null ? emptyCollection() : collection;
  727.     }

  728.     /**
  729.      * Answers true if a predicate is true for at least one element of a
  730.      * collection.
  731.      * <p>
  732.      * A {@code null} collection or predicate returns false.
  733.      * </p>
  734.      *
  735.      * @param <C>  the type of object the {@link Iterable} contains
  736.      * @param input  the {@link Iterable} to get the input from, may be null
  737.      * @param predicate  the predicate to use, may be null
  738.      * @return true if at least one element of the collection matches the predicate
  739.      * @deprecated since 4.1, use {@link IterableUtils#matchesAny(Iterable, Predicate)} instead
  740.      */
  741.     @Deprecated
  742.     public static <C> boolean exists(final Iterable<C> input, final Predicate<? super C> predicate) {
  743.         return predicate != null && IterableUtils.matchesAny(input, predicate);
  744.     }

  745.     /**
  746.      * Extract the lone element of the specified Collection.
  747.      *
  748.      * @param <E> collection type
  749.      * @param collection to read
  750.      * @return sole member of collection
  751.      * @throws NullPointerException if collection is null
  752.      * @throws IllegalArgumentException if collection is empty or contains more than one element
  753.      * @since 4.0
  754.      */
  755.     public static <E> E extractSingleton(final Collection<E> collection) {
  756.         Objects.requireNonNull(collection, "collection");
  757.         if (collection.size() != 1) {
  758.             throw new IllegalArgumentException("Can extract singleton only when collection size == 1");
  759.         }
  760.         return collection.iterator().next();
  761.     }

  762.     /**
  763.      * Filter the collection by applying a Predicate to each element. If the
  764.      * predicate returns false, remove the element.
  765.      * <p>
  766.      * If the input collection or predicate is null, there is no change made.
  767.      * </p>
  768.      *
  769.      * @param <T>  the type of object the {@link Iterable} contains
  770.      * @param collection  the collection to get the input from, may be null
  771.      * @param predicate  the predicate to use as a filter, may be null
  772.      * @return true if the collection is modified by this call, false otherwise.
  773.      */
  774.     public static <T> boolean filter(final Iterable<T> collection, final Predicate<? super T> predicate) {
  775.         boolean result = false;
  776.         if (collection != null && predicate != null) {
  777.             for (final Iterator<T> it = collection.iterator(); it.hasNext();) {
  778.                 if (!predicate.test(it.next())) {
  779.                     it.remove();
  780.                     result = true;
  781.                 }
  782.             }
  783.         }
  784.         return result;
  785.     }

  786.     /**
  787.      * Filter the collection by applying a Predicate to each element. If the
  788.      * predicate returns true, remove the element.
  789.      * <p>
  790.      * This is equivalent to {@code filter(collection, PredicateUtils.notPredicate(predicate))}
  791.      * if predicate is != null.
  792.      * </p>
  793.      * <p>
  794.      * If the input collection or predicate is null, there is no change made.
  795.      * </p>
  796.      *
  797.      * @param <T>  the type of object the {@link Iterable} contains
  798.      * @param collection  the collection to get the input from, may be null
  799.      * @param predicate  the predicate to use as a filter, may be null
  800.      * @return true if the collection is modified by this call, false otherwise.
  801.      */
  802.     public static <T> boolean filterInverse(final Iterable<T> collection, final Predicate<? super T> predicate) {
  803.         return filter(collection, predicate == null ? null : PredicateUtils.notPredicate(predicate));
  804.     }

  805.     /**
  806.      * Finds the first element in the given collection which matches the given predicate.
  807.      * <p>
  808.      * If the input collection or predicate is null, or no element of the collection
  809.      * matches the predicate, null is returned.
  810.      * </p>
  811.      *
  812.      * @param <T>  the type of object the {@link Iterable} contains
  813.      * @param collection  the collection to search, may be null
  814.      * @param predicate  the predicate to use, may be null
  815.      * @return the first element of the collection which matches the predicate or null if none could be found
  816.      * @deprecated since 4.1, use {@link IterableUtils#find(Iterable, Predicate)} instead
  817.      */
  818.     @Deprecated
  819.     public static <T> T find(final Iterable<T> collection, final Predicate<? super T> predicate) {
  820.         return predicate != null ? IterableUtils.find(collection, predicate) : null;
  821.     }

  822.     /**
  823.      * Executes the given closure on each but the last element in the collection.
  824.      * <p>
  825.      * If the input collection or closure is null, there is no change made.
  826.      * </p>
  827.      *
  828.      * @param <T>  the type of object the {@link Iterable} contains
  829.      * @param <C>  the closure type
  830.      * @param collection  the collection to get the input from, may be null
  831.      * @param closure  the closure to perform, may be null
  832.      * @return the last element in the collection, or null if either collection or closure is null
  833.      * @since 4.0
  834.      * @deprecated since 4.1, use {@link IterableUtils#forEachButLast(Iterable, Closure)} instead
  835.      */
  836.     @Deprecated
  837.     public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterable<T> collection,
  838.                                                                       final C closure) {
  839.         return closure != null ? IterableUtils.forEachButLast(collection, closure) : null;
  840.     }

  841.     /**
  842.      * Executes the given closure on each but the last element in the collection.
  843.      * <p>
  844.      * If the input collection or closure is null, there is no change made.
  845.      * </p>
  846.      *
  847.      * @param <T>  the type of object the {@link Collection} contains
  848.      * @param <C>  the closure type
  849.      * @param iterator  the iterator to get the input from, may be null
  850.      * @param closure  the closure to perform, may be null
  851.      * @return the last element in the collection, or null if either iterator or closure is null
  852.      * @since 4.0
  853.      * @deprecated since 4.1, use {@link IteratorUtils#forEachButLast(Iterator, Closure)} instead
  854.      */
  855.     @Deprecated
  856.     public static <T, C extends Closure<? super T>> T forAllButLastDo(final Iterator<T> iterator, final C closure) {
  857.         return closure != null ? IteratorUtils.forEachButLast(iterator, closure) : null;
  858.     }

  859.     /**
  860.      * Executes the given closure on each element in the collection.
  861.      * <p>
  862.      * If the input collection or closure is null, there is no change made.
  863.      * </p>
  864.      *
  865.      * @param <T>  the type of object the {@link Iterable} contains
  866.      * @param <C>  the closure type
  867.      * @param collection  the collection to get the input from, may be null
  868.      * @param closure  the closure to perform, may be null
  869.      * @return closure
  870.      * @deprecated since 4.1, use {@link IterableUtils#forEach(Iterable, Closure)} instead
  871.      */
  872.     @Deprecated
  873.     public static <T, C extends Closure<? super T>> C forAllDo(final Iterable<T> collection, final C closure) {
  874.         if (closure != null) {
  875.             IterableUtils.forEach(collection, closure);
  876.         }
  877.         return closure;
  878.     }

  879.     /**
  880.      * Executes the given closure on each element in the collection.
  881.      * <p>
  882.      * If the input collection or closure is null, there is no change made.
  883.      * </p>
  884.      *
  885.      * @param <T>  the type of object the {@link Iterator} contains
  886.      * @param <C>  the closure type
  887.      * @param iterator  the iterator to get the input from, may be null
  888.      * @param closure  the closure to perform, may be null
  889.      * @return closure
  890.      * @since 4.0
  891.      * @deprecated since 4.1, use {@link IteratorUtils#forEach(Iterator, Closure)} instead
  892.      */
  893.     @Deprecated
  894.     public static <T, C extends Closure<? super T>> C forAllDo(final Iterator<T> iterator, final C closure) {
  895.         if (closure != null) {
  896.             IteratorUtils.forEach(iterator, closure);
  897.         }
  898.         return closure;
  899.     }

  900.     /**
  901.      * Gets the {@code index}-th value in the {@code iterable}'s {@link Iterator}, throwing
  902.      * {@code IndexOutOfBoundsException} if there is no such element.
  903.      * <p>
  904.      * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}.
  905.      * </p>
  906.      *
  907.      * @param iterable  the {@link Iterable} to get a value from
  908.      * @param index  the index to get
  909.      * @param <T> the type of object in the {@link Iterable}.
  910.      * @return the object at the specified index
  911.      * @throws IndexOutOfBoundsException if the index is invalid
  912.      * @deprecated since 4.1, use {@code IterableUtils.get(Iterable, int)} instead
  913.      */
  914.     @Deprecated
  915.     public static <T> T get(final Iterable<T> iterable, final int index) {
  916.         Objects.requireNonNull(iterable, "iterable");
  917.         return IterableUtils.get(iterable, index);
  918.     }

  919.     /**
  920.      * Gets the {@code index}-th value in {@link Iterator}, throwing
  921.      * {@code IndexOutOfBoundsException} if there is no such element.
  922.      * <p>
  923.      * The Iterator is advanced to {@code index} (or to the end, if
  924.      * {@code index} exceeds the number of entries) as a side effect of this method.
  925.      * </p>
  926.      *
  927.      * @param iterator  the iterator to get a value from
  928.      * @param index  the index to get
  929.      * @param <T> the type of object in the {@link Iterator}
  930.      * @return the object at the specified index
  931.      * @throws IndexOutOfBoundsException if the index is invalid
  932.      * @throws IllegalArgumentException if the object type is invalid
  933.      * @throws NullPointerException if iterator is null
  934.      * @deprecated since 4.1, use {@code IteratorUtils.get(Iterator, int)} instead
  935.      */
  936.     @Deprecated
  937.     public static <T> T get(final Iterator<T> iterator, final int index) {
  938.         Objects.requireNonNull(iterator, "iterator");
  939.         return IteratorUtils.get(iterator, index);
  940.     }

  941.     /**
  942.      * Gets the {@code index}-th {@code Map.Entry} in the {@code map}'s {@code entrySet},
  943.      * throwing {@code IndexOutOfBoundsException} if there is no such element.
  944.      *
  945.      * @param <K>  the key type in the {@link Map}
  946.      * @param <V>  the value type in the {@link Map}
  947.      * @param map  the object to get a value from
  948.      * @param index  the index to get
  949.      * @return the object at the specified index
  950.      * @throws IndexOutOfBoundsException if the index is invalid
  951.      */
  952.     public static <K, V> Map.Entry<K, V> get(final Map<K, V> map, final int index) {
  953.         Objects.requireNonNull(map, "map");
  954.         checkIndexBounds(index);
  955.         return get(map.entrySet(), index);
  956.     }

  957.     /**
  958.      * Gets the {@code index}-th value in {@code object}, throwing
  959.      * {@code IndexOutOfBoundsException} if there is no such element or
  960.      * {@code IllegalArgumentException} if {@code object} is not an
  961.      * instance of one of the supported types.
  962.      * <p>
  963.      * The supported types, and associated semantics are:
  964.      * </p>
  965.      * <ul>
  966.      * <li> Map -- the value returned is the {@code Map.Entry} in position
  967.      *      {@code index} in the map's {@code entrySet} iterator,
  968.      *      if there is such an entry.</li>
  969.      * <li> List -- this method is equivalent to the list's get method.</li>
  970.      * <li> Array -- the {@code index}-th array entry is returned,
  971.      *      if there is such an entry; otherwise an {@code IndexOutOfBoundsException}
  972.      *      is thrown.</li>
  973.      * <li> Collection -- the value returned is the {@code index}-th object
  974.      *      returned by the collection's default iterator, if there is such an element.</li>
  975.      * <li> Iterator or Enumeration -- the value returned is the
  976.      *      {@code index}-th object in the Iterator/Enumeration, if there
  977.      *      is such an element.  The Iterator/Enumeration is advanced to
  978.      *      {@code index} (or to the end, if {@code index} exceeds the
  979.      *      number of entries) as a side effect of this method.</li>
  980.      * </ul>
  981.      *
  982.      * @param object  the object to get a value from
  983.      * @param index  the index to get
  984.      * @return the object at the specified index
  985.      * @throws IndexOutOfBoundsException if the index is invalid
  986.      * @throws IllegalArgumentException if the object type is invalid
  987.      */
  988.     public static Object get(final Object object, final int index) {
  989.         final int i = index;
  990.         if (i < 0) {
  991.             throw new IndexOutOfBoundsException("Index cannot be negative: " + i);
  992.         }
  993.         if (object instanceof Map<?, ?>) {
  994.             final Map<?, ?> map = (Map<?, ?>) object;
  995.             final Iterator<?> iterator = map.entrySet().iterator();
  996.             return IteratorUtils.get(iterator, i);
  997.         }
  998.         if (object instanceof Object[]) {
  999.             return ((Object[]) object)[i];
  1000.         }
  1001.         if (object instanceof Iterator<?>) {
  1002.             final Iterator<?> it = (Iterator<?>) object;
  1003.             return IteratorUtils.get(it, i);
  1004.         }
  1005.         if (object instanceof Iterable<?>) {
  1006.             final Iterable<?> iterable = (Iterable<?>) object;
  1007.             return IterableUtils.get(iterable, i);
  1008.         }
  1009.         if (object instanceof Enumeration<?>) {
  1010.             final Enumeration<?> it = (Enumeration<?>) object;
  1011.             return EnumerationUtils.get(it, i);
  1012.         }
  1013.         if (object == null) {
  1014.             throw new IllegalArgumentException("Unsupported object type: null");
  1015.         }
  1016.         try {
  1017.             return Array.get(object, i);
  1018.         } catch (final IllegalArgumentException ex) {
  1019.             throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
  1020.         }
  1021.     }

  1022.     /**
  1023.      * Gets a {@link Map} mapping each unique element in the given
  1024.      * {@link Collection} to an {@link Integer} representing the number
  1025.      * of occurrences of that element in the {@link Collection}.
  1026.      * <p>
  1027.      * Only those elements present in the collection will appear as
  1028.      * keys in the map.
  1029.      * </p>
  1030.      *
  1031.      * @param <O>  the type of object in the returned {@link Map}. This is a super type of &lt;I&gt;.
  1032.      * @param coll  the collection to get the cardinality map for, must not be null
  1033.      * @return the populated cardinality map
  1034.      * @throws NullPointerException if coll is null
  1035.      */
  1036.     public static <O> Map<O, Integer> getCardinalityMap(final Iterable<? extends O> coll) {
  1037.         Objects.requireNonNull(coll, "coll");
  1038.         final Map<O, Integer> count = new HashMap<>();
  1039.         for (final O obj : coll) {
  1040.             final Integer c = count.get(obj);
  1041.             if (c == null) {
  1042.                 count.put(obj, Integer.valueOf(1));
  1043.             } else {
  1044.                 count.put(obj, Integer.valueOf(c.intValue() + 1));
  1045.             }
  1046.         }
  1047.         return count;
  1048.     }

  1049.     /**
  1050.      * Returns the hash code of the input collection using the hash method of an equator.
  1051.      *
  1052.      * <p>
  1053.      * Returns 0 if the input collection is {@code null}.
  1054.      * </p>
  1055.      *
  1056.      * @param <E>  the element type
  1057.      * @param collection  the input collection
  1058.      * @param equator  the equator used for generate hashCode
  1059.      * @return the hash code of the input collection using the hash method of an equator
  1060.      * @throws NullPointerException if the equator is {@code null}
  1061.      * @since 4.5.0-M1
  1062.      */
  1063.     public static <E> int hashCode(final Collection<? extends E> collection,
  1064.             final Equator<? super E> equator) {
  1065.         Objects.requireNonNull(equator, "equator");
  1066.         if (null == collection) {
  1067.             return 0;
  1068.         }
  1069.         int hashCode = 1;
  1070.         for (final E e : collection) {
  1071.             hashCode = 31 * hashCode + equator.hash(e);
  1072.         }
  1073.         return hashCode;
  1074.     }

  1075.     /**
  1076.      * Returns a {@link Collection} containing the intersection of the given
  1077.      * {@link Iterable}s.
  1078.      * <p>
  1079.      * The cardinality of each element in the returned {@link Collection} will
  1080.      * be equal to the minimum of the cardinality of that element in the two
  1081.      * given {@link Iterable}s.
  1082.      * </p>
  1083.      *
  1084.      * @param a the first collection, must not be null
  1085.      * @param b the second collection, must not be null
  1086.      * @param <O> the generic type that is able to represent the types contained
  1087.      *        in both input collections.
  1088.      * @return the intersection of the two collections
  1089.      * @throws NullPointerException if either collection is null
  1090.      * @see Collection#retainAll
  1091.      * @see #containsAny
  1092.      */
  1093.     public static <O> Collection<O> intersection(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  1094.         Objects.requireNonNull(a, "a");
  1095.         Objects.requireNonNull(b, "b");
  1096.         final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
  1097.         for (final O obj : helper) {
  1098.             helper.setCardinality(obj, helper.min(obj));
  1099.         }
  1100.         return helper.list();
  1101.     }

  1102.     /**
  1103.      * Null-safe check if the specified collection is empty.
  1104.      * <p>
  1105.      * Null returns true.
  1106.      * </p>
  1107.      *
  1108.      * @param coll  the collection to check, may be null
  1109.      * @return true if empty or null
  1110.      * @since 3.2
  1111.      */
  1112.     public static boolean isEmpty(final Collection<?> coll) {
  1113.         return coll == null || coll.isEmpty();
  1114.     }

  1115.     /**
  1116.      * Returns {@code true} iff the given {@link Collection}s contain
  1117.      * exactly the same elements with exactly the same cardinalities.
  1118.      * <p>
  1119.      * That is, iff the cardinality of <em>e</em> in <em>a</em> is
  1120.      * equal to the cardinality of <em>e</em> in <em>b</em>,
  1121.      * for each element <em>e</em> in <em>a</em> or <em>b</em>.
  1122.      * </p>
  1123.      *
  1124.      * @param a  the first collection, must not be null
  1125.      * @param b  the second collection, must not be null
  1126.      * @return {@code true} iff the collections contain the same elements with the same cardinalities.
  1127.      * @throws NullPointerException if either collection is null
  1128.      */
  1129.     public static boolean isEqualCollection(final Collection<?> a, final Collection<?> b) {
  1130.         return CardinalityHelper.equals(a, b);
  1131.     }

  1132.     /**
  1133.      * Returns {@code true} iff the given {@link Collection}s contain
  1134.      * exactly the same elements with exactly the same cardinalities.
  1135.      * <p>
  1136.      * That is, iff the cardinality of <em>e</em> in <em>a</em> is
  1137.      * equal to the cardinality of <em>e</em> in <em>b</em>,
  1138.      * for each element <em>e</em> in <em>a</em> or <em>b</em>.
  1139.      * </p>
  1140.      * <p>
  1141.      * <strong>Note:</strong> from version 4.1 onwards this method requires the input
  1142.      * collections and equator to be of compatible type (using bounded wildcards).
  1143.      * Providing incompatible arguments (for example by casting to their rawtypes)
  1144.      * will result in a {@code ClassCastException} thrown at runtime.
  1145.      * </p>
  1146.      *
  1147.      * @param <E>  the element type
  1148.      * @param a  the first collection, must not be null
  1149.      * @param b  the second collection, must not be null
  1150.      * @param equator  the Equator used for testing equality
  1151.      * @return {@code true} iff the collections contain the same elements with the same cardinalities.
  1152.      * @throws NullPointerException if either collection or equator is null
  1153.      * @since 4.0
  1154.      */
  1155.     public static <E> boolean isEqualCollection(final Collection<? extends E> a,
  1156.                                                 final Collection<? extends E> b,
  1157.                                                 final Equator<? super E> equator) {
  1158.         Objects.requireNonNull(a, "a");
  1159.         Objects.requireNonNull(b, "b");
  1160.         Objects.requireNonNull(equator, "equator");

  1161.         if (a.size() != b.size()) {
  1162.             return false;
  1163.         }

  1164.         @SuppressWarnings({ "unchecked", "rawtypes" })
  1165.         final Transformer<E, ?> transformer = input -> new EquatorWrapper(equator, input);

  1166.         return isEqualCollection(collect(a, transformer), collect(b, transformer));
  1167.     }

  1168.     /**
  1169.      * Returns true if no more elements can be added to the Collection.
  1170.      * <p>
  1171.      * This method uses the {@link BoundedCollection} interface to determine the
  1172.      * full status. If the collection does not implement this interface then
  1173.      * false is returned.
  1174.      * </p>
  1175.      * <p>
  1176.      * The collection does not have to implement this interface directly.
  1177.      * If the collection has been decorated using the decorators subpackage
  1178.      * then these will be removed to access the BoundedCollection.
  1179.      * </p>
  1180.      *
  1181.      * @param collection  the collection to check
  1182.      * @return true if the BoundedCollection is full
  1183.      * @throws NullPointerException if the collection is null
  1184.      */
  1185.     public static boolean isFull(final Collection<? extends Object> collection) {
  1186.         Objects.requireNonNull(collection, "collection");
  1187.         if (collection instanceof BoundedCollection) {
  1188.             return ((BoundedCollection<?>) collection).isFull();
  1189.         }
  1190.         try {
  1191.             final BoundedCollection<?> bcoll =
  1192.                     UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
  1193.             return bcoll.isFull();
  1194.         } catch (final IllegalArgumentException ex) {
  1195.             return false;
  1196.         }
  1197.     }

  1198.     /**
  1199.      * Null-safe check if the specified collection is not empty.
  1200.      * <p>
  1201.      * Null returns false.
  1202.      * </p>
  1203.      *
  1204.      * @param coll  the collection to check, may be null
  1205.      * @return true if non-null and non-empty
  1206.      * @since 3.2
  1207.      */
  1208.     public static boolean isNotEmpty(final Collection<?> coll) {
  1209.         return !isEmpty(coll);
  1210.     }

  1211.     /**
  1212.      * Returns {@code true} iff <em>a</em> is a <em>proper</em> sub-collection of <em>b</em>,
  1213.      * that is, iff the cardinality of <em>e</em> in <em>a</em> is less
  1214.      * than or equal to the cardinality of <em>e</em> in <em>b</em>,
  1215.      * for each element <em>e</em> in <em>a</em>, and there is at least one
  1216.      * element <em>f</em> such that the cardinality of <em>f</em> in <em>b</em>
  1217.      * is strictly greater than the cardinality of <em>f</em> in <em>a</em>.
  1218.      * <p>
  1219.      * The implementation assumes
  1220.      * </p>
  1221.      * <ul>
  1222.      *    <li>{@code a.size()} and {@code b.size()} represent the
  1223.      *    total cardinality of <em>a</em> and <em>b</em>, resp. </li>
  1224.      *    <li>{@code a.size() &lt; Integer.MAXVALUE}</li>
  1225.      * </ul>
  1226.      *
  1227.      * @param a  the first (sub?) collection, must not be null
  1228.      * @param b  the second (super?) collection, must not be null
  1229.      * @return {@code true} iff <em>a</em> is a <em>proper</em> sub-collection of <em>b</em>
  1230.      * @throws NullPointerException if either collection is null
  1231.      * @see #isSubCollection
  1232.      * @see Collection#containsAll
  1233.      */
  1234.     public static boolean isProperSubCollection(final Collection<?> a, final Collection<?> b) {
  1235.         Objects.requireNonNull(a, "a");
  1236.         Objects.requireNonNull(b, "b");
  1237.         return a.size() < b.size() && isSubCollection(a, b);
  1238.     }

  1239.     /**
  1240.      * Returns {@code true} iff <em>a</em> is a sub-collection of <em>b</em>,
  1241.      * that is, iff the cardinality of <em>e</em> in <em>a</em> is less than or
  1242.      * equal to the cardinality of <em>e</em> in <em>b</em>, for each element <em>e</em>
  1243.      * in <em>a</em>.
  1244.      *
  1245.      * @param a the first (sub?) collection, must not be null
  1246.      * @param b the second (super?) collection, must not be null
  1247.      * @return {@code true} iff <em>a</em> is a sub-collection of <em>b</em>
  1248.      * @throws NullPointerException if either collection is null
  1249.      * @see #isProperSubCollection
  1250.      * @see Collection#containsAll
  1251.      */
  1252.     public static boolean isSubCollection(final Collection<?> a, final Collection<?> b) {
  1253.         Objects.requireNonNull(a, "a");
  1254.         Objects.requireNonNull(b, "b");
  1255.         final CardinalityHelper<Object> helper = new CardinalityHelper<>(a, b);
  1256.         for (final Object obj : a) {
  1257.             if (helper.freqA(obj) > helper.freqB(obj)) {
  1258.                 return false;
  1259.             }
  1260.         }
  1261.         return true;
  1262.     }

  1263.     /**
  1264.      * Answers true if a predicate is true for every element of a
  1265.      * collection.
  1266.      *
  1267.      * <p>
  1268.      * A {@code null} predicate returns false.
  1269.      * </p>
  1270.      * <p>
  1271.      * A {@code null} or empty collection returns true.
  1272.      * </p>
  1273.      *
  1274.      * @param <C>  the type of object the {@link Iterable} contains
  1275.      * @param input  the {@link Iterable} to get the input from, may be null
  1276.      * @param predicate  the predicate to use, may be null
  1277.      * @return true if every element of the collection matches the predicate or if the
  1278.      * collection is empty, false otherwise
  1279.      * @since 4.0
  1280.      * @deprecated since 4.1, use {@link IterableUtils#matchesAll(Iterable, Predicate)} instead
  1281.      */
  1282.     @Deprecated
  1283.     public static <C> boolean matchesAll(final Iterable<C> input, final Predicate<? super C> predicate) {
  1284.         return predicate != null && IterableUtils.matchesAll(input, predicate);
  1285.     }

  1286.     /**
  1287.      * Gets the maximum number of elements that the Collection can contain.
  1288.      * <p>
  1289.      * This method uses the {@link BoundedCollection} interface to determine the
  1290.      * maximum size. If the collection does not implement this interface then
  1291.      * -1 is returned.
  1292.      * </p>
  1293.      * <p>
  1294.      * The collection does not have to implement this interface directly.
  1295.      * If the collection has been decorated using the decorators subpackage
  1296.      * then these will be removed to access the BoundedCollection.
  1297.      * </p>
  1298.      *
  1299.      * @param collection  the collection to check
  1300.      * @return the maximum size of the BoundedCollection, -1 if no maximum size
  1301.      * @throws NullPointerException if the collection is null
  1302.      */
  1303.     public static int maxSize(final Collection<? extends Object> collection) {
  1304.         Objects.requireNonNull(collection, "collection");
  1305.         if (collection instanceof BoundedCollection) {
  1306.             return ((BoundedCollection<?>) collection).maxSize();
  1307.         }
  1308.         try {
  1309.             final BoundedCollection<?> bcoll =
  1310.                     UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection);
  1311.             return bcoll.maxSize();
  1312.         } catch (final IllegalArgumentException ex) {
  1313.             return -1;
  1314.         }
  1315.     }

  1316.     /**
  1317.      * Returns a {@link Collection} of all the permutations of the input collection.
  1318.      * <p>
  1319.      * NOTE: the number of permutations of a given collection is equal to n!, where
  1320.      * n is the size of the collection. Thus, the resulting collection will become
  1321.      * <strong>very</strong> large for collections &gt; 10 (for example 10! = 3628800, 15! = 1307674368000).
  1322.      * </p>
  1323.      * <p>
  1324.      * For larger collections it is advised to use a {@link PermutationIterator} to
  1325.      * iterate over all permutations.
  1326.      * </p>
  1327.      *
  1328.      * @see PermutationIterator
  1329.      * @param <E>  the element type
  1330.      * @param collection  the collection to create permutations for, must not be null
  1331.      * @return an unordered collection of all permutations of the input collection
  1332.      * @throws NullPointerException if collection is null
  1333.      * @since 4.0
  1334.      */
  1335.     public static <E> Collection<List<E>> permutations(final Collection<E> collection) {
  1336.         Objects.requireNonNull(collection, "collection");
  1337.         final PermutationIterator<E> it = new PermutationIterator<>(collection);
  1338.         final Collection<List<E>> result = new ArrayList<>();
  1339.         while (it.hasNext()) {
  1340.             result.add(it.next());
  1341.         }
  1342.         return result;
  1343.     }

  1344.     /**
  1345.      * Returns a predicated (validating) collection backed by the given collection.
  1346.      * <p>
  1347.      * Only objects that pass the test in the given predicate can be added to the collection.
  1348.      * Trying to add an invalid object results in an IllegalArgumentException.
  1349.      * It is important not to use the original collection after invoking this method,
  1350.      * as it is a backdoor for adding invalid objects.
  1351.      * </p>
  1352.      *
  1353.      * @param <C> the type of objects in the Collection.
  1354.      * @param collection  the collection to predicate, must not be null
  1355.      * @param predicate  the predicate for the collection, must not be null
  1356.      * @return a predicated collection backed by the given collection
  1357.      * @throws NullPointerException if the collection or predicate is null
  1358.      */
  1359.     public static <C> Collection<C> predicatedCollection(final Collection<C> collection,
  1360.                                                          final Predicate<? super C> predicate) {
  1361.         Objects.requireNonNull(collection, "collection");
  1362.         Objects.requireNonNull(predicate, "predicate");
  1363.         return PredicatedCollection.predicatedCollection(collection, predicate);
  1364.     }

  1365.     /**
  1366.      * Removes the elements in {@code remove} from {@code collection}. That is, this
  1367.      * method returns a collection containing all the elements in {@code c}
  1368.      * that are not in {@code remove}. The cardinality of an element {@code e}
  1369.      * in the returned collection is the same as the cardinality of {@code e}
  1370.      * in {@code collection} unless {@code remove} contains {@code e}, in which
  1371.      * case the cardinality is zero. This method is useful if you do not wish to modify
  1372.      * the collection {@code c} and thus cannot call {@code collection.removeAll(remove);}.
  1373.      * <p>
  1374.      * This implementation iterates over {@code collection}, checking each element in
  1375.      * turn to see if it's contained in {@code remove}. If it's not contained, it's added
  1376.      * to the returned list. As a consequence, it is advised to use a collection type for
  1377.      * {@code remove} that provides a fast (for example O(1)) implementation of
  1378.      * {@link Collection#contains(Object)}.
  1379.      * </p>
  1380.      *
  1381.      * @param <E>  the type of object the {@link Collection} contains
  1382.      * @param collection  the collection from which items are removed (in the returned collection)
  1383.      * @param remove  the items to be removed from the returned {@code collection}
  1384.      * @return a {@code Collection} containing all the elements of {@code collection} except
  1385.      * any elements that also occur in {@code remove}.
  1386.      * @throws NullPointerException if either parameter is null
  1387.      * @since 4.0 (method existed in 3.2 but was completely broken)
  1388.      */
  1389.     public static <E> Collection<E> removeAll(final Collection<E> collection, final Collection<?> remove) {
  1390.         return ListUtils.removeAll(collection, remove);
  1391.     }

  1392.     /**
  1393.      * Removes all elements in {@code remove} from {@code collection}.
  1394.      * That is, this method returns a collection containing all the elements in
  1395.      * {@code collection} that are not in {@code remove}. The
  1396.      * cardinality of an element {@code e} in the returned collection is
  1397.      * the same as the cardinality of {@code e} in {@code collection}
  1398.      * unless {@code remove} contains {@code e}, in which case the
  1399.      * cardinality is zero. This method is useful if you do not wish to modify
  1400.      * the collection {@code c} and thus cannot call
  1401.      * {@code collection.removeAll(remove)}.
  1402.      * <p>
  1403.      * Moreover this method uses an {@link Equator} instead of
  1404.      * {@link Object#equals(Object)} to determine the equality of the elements
  1405.      * in {@code collection} and {@code remove}. Hence this method is
  1406.      * useful in cases where the equals behavior of an object needs to be
  1407.      * modified without changing the object itself.
  1408.      * </p>
  1409.      *
  1410.      * @param <E> the type of object the {@link Collection} contains
  1411.      * @param collection the collection from which items are removed (in the returned collection)
  1412.      * @param remove the items to be removed from the returned collection
  1413.      * @param equator the Equator used for testing equality
  1414.      * @return a {@code Collection} containing all the elements of {@code collection}
  1415.      * except any element that if equal according to the {@code equator}
  1416.      * @throws NullPointerException if any of the parameters is null
  1417.      * @since 4.1
  1418.      */
  1419.     public static <E> Collection<E> removeAll(final Iterable<E> collection,
  1420.                                               final Iterable<? extends E> remove,
  1421.                                               final Equator<? super E> equator) {
  1422.         Objects.requireNonNull(collection, "collection");
  1423.         Objects.requireNonNull(remove, "remove");
  1424.         Objects.requireNonNull(equator, "equator");
  1425.         final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);

  1426.         final Set<EquatorWrapper<E>> removeSet =
  1427.                 collect(remove, transformer, new HashSet<>());

  1428.         final List<E> list = new ArrayList<>();
  1429.         for (final E element : collection) {
  1430.             if (!removeSet.contains(new EquatorWrapper<>(equator, element))) {
  1431.                 list.add(element);
  1432.             }
  1433.         }
  1434.         return list;
  1435.     }

  1436.     /**
  1437.      * Removes the specified number of elements from the start index in the collection and returns them.
  1438.      * This method modifies the input collections.
  1439.      *
  1440.      * @param <E>  the type of object the {@link Collection} contains
  1441.      * @param input  the collection will be operated, can't be null
  1442.      * @param startIndex  the start index (inclusive) to remove element, can't be less than 0
  1443.      * @param count  the specified number to remove, can't be less than 1
  1444.      * @return collection of elements that removed from the input collection
  1445.      * @throws NullPointerException if input is null
  1446.      * @since 4.5.0-M1
  1447.      */
  1448.     public static <E> Collection<E> removeCount(final Collection<E> input, int startIndex, int count) {
  1449.         Objects.requireNonNull(input, "input");
  1450.         if (startIndex < 0) {
  1451.             throw new IndexOutOfBoundsException("The start index can't be less than 0.");
  1452.         }
  1453.         if (count < 0) {
  1454.             throw new IndexOutOfBoundsException("The count can't be less than 0.");
  1455.         }
  1456.         if (input.size() < startIndex + count) {
  1457.             throw new IndexOutOfBoundsException(
  1458.                     "The sum of start index and count can't be greater than the size of collection.");
  1459.         }

  1460.         final Collection<E> result = new ArrayList<>(count);
  1461.         final Iterator<E> iterator = input.iterator();
  1462.         while (count > 0) {
  1463.             if (startIndex > 0) {
  1464.                 startIndex -= 1;
  1465.                 iterator.next();
  1466.                 continue;
  1467.             }
  1468.             count -= 1;
  1469.             result.add(iterator.next());
  1470.             iterator.remove();
  1471.         }
  1472.         return result;
  1473.     }

  1474.     /**
  1475.      * Removes elements whose index are between startIndex, inclusive and endIndex,
  1476.      * exclusive in the collection and returns them.
  1477.      * This method modifies the input collections.
  1478.      *
  1479.      * @param <E>  the type of object the {@link Collection} contains
  1480.      * @param input  the collection will be operated, must not be null
  1481.      * @param startIndex  the start index (inclusive) to remove element, must not be less than 0
  1482.      * @param endIndex  the end index (exclusive) to remove, must not be less than startIndex
  1483.      * @return collection of elements that removed from the input collection
  1484.      * @throws NullPointerException if input is null
  1485.      * @since 4.5.0-M1
  1486.      */
  1487.     public static <E> Collection<E> removeRange(final Collection<E> input, final int startIndex, final int endIndex) {
  1488.         Objects.requireNonNull(input, "input");
  1489.         if (endIndex < startIndex) {
  1490.             throw new IllegalArgumentException("The end index can't be less than the start index.");
  1491.         }
  1492.         if (input.size() < endIndex) {
  1493.             throw new IndexOutOfBoundsException("The end index can't be greater than the size of collection.");
  1494.         }
  1495.         return removeCount(input, startIndex, endIndex - startIndex);
  1496.     }

  1497.     /**
  1498.      * Returns a collection containing all the elements in {@code collection}
  1499.      * that are also in {@code retain}. The cardinality of an element {@code e}
  1500.      * in the returned collection is the same as the cardinality of {@code e}
  1501.      * in {@code collection} unless {@code retain} does not contain {@code e}, in which
  1502.      * case the cardinality is zero. This method is useful if you do not wish to modify
  1503.      * the collection {@code c} and thus cannot call {@code c.retainAll(retain);}.
  1504.      * <p>
  1505.      * This implementation iterates over {@code collection}, checking each element in
  1506.      * turn to see if it's contained in {@code retain}. If it's contained, it's added
  1507.      * to the returned list. As a consequence, it is advised to use a collection type for
  1508.      * {@code retain} that provides a fast (for example O(1)) implementation of
  1509.      * {@link Collection#contains(Object)}.
  1510.      * </p>
  1511.      *
  1512.      * @param <C>  the type of object the {@link Collection} contains
  1513.      * @param collection  the collection whose contents are the target of the #retailAll operation
  1514.      * @param retain  the collection containing the elements to be retained in the returned collection
  1515.      * @return a {@code Collection} containing all the elements of {@code collection}
  1516.      * that occur at least once in {@code retain}.
  1517.      * @throws NullPointerException if either parameter is null
  1518.      * @since 3.2
  1519.      */
  1520.     public static <C> Collection<C> retainAll(final Collection<C> collection, final Collection<?> retain) {
  1521.         Objects.requireNonNull(collection, "collection");
  1522.         Objects.requireNonNull(retain, "retain");
  1523.         return ListUtils.retainAll(collection, retain);
  1524.     }

  1525.     /**
  1526.      * Returns a collection containing all the elements in
  1527.      * {@code collection} that are also in {@code retain}. The
  1528.      * cardinality of an element {@code e} in the returned collection is
  1529.      * the same as the cardinality of {@code e} in {@code collection}
  1530.      * unless {@code retain} does not contain {@code e}, in which case
  1531.      * the cardinality is zero. This method is useful if you do not wish to
  1532.      * modify the collection {@code c} and thus cannot call
  1533.      * {@code c.retainAll(retain);}.
  1534.      * <p>
  1535.      * Moreover this method uses an {@link Equator} instead of
  1536.      * {@link Object#equals(Object)} to determine the equality of the elements
  1537.      * in {@code collection} and {@code retain}. Hence this method is
  1538.      * useful in cases where the equals behavior of an object needs to be
  1539.      * modified without changing the object itself.
  1540.      * </p>
  1541.      *
  1542.      * @param <E> the type of object the {@link Collection} contains
  1543.      * @param collection the collection whose contents are the target of the {@code retainAll} operation
  1544.      * @param retain the collection containing the elements to be retained in the returned collection
  1545.      * @param equator the Equator used for testing equality
  1546.      * @return a {@code Collection} containing all the elements of {@code collection}
  1547.      * that occur at least once in {@code retain} according to the {@code equator}
  1548.      * @throws NullPointerException if any of the parameters is null
  1549.      * @since 4.1
  1550.      */
  1551.     public static <E> Collection<E> retainAll(final Iterable<E> collection,
  1552.                                               final Iterable<? extends E> retain,
  1553.                                               final Equator<? super E> equator) {
  1554.         Objects.requireNonNull(collection, "collection");
  1555.         Objects.requireNonNull(retain, "retain");
  1556.         Objects.requireNonNull(equator, "equator");
  1557.         final Transformer<E, EquatorWrapper<E>> transformer = input -> new EquatorWrapper<>(equator, input);

  1558.         final Set<EquatorWrapper<E>> retainSet =
  1559.                 collect(retain, transformer, new HashSet<>());

  1560.         final List<E> list = new ArrayList<>();
  1561.         for (final E element : collection) {
  1562.             if (retainSet.contains(new EquatorWrapper<>(equator, element))) {
  1563.                 list.add(element);
  1564.             }
  1565.         }
  1566.         return list;
  1567.     }

  1568.     /**
  1569.      * Reverses the order of the given array.
  1570.      *
  1571.      * @param array  the array to reverse
  1572.      */
  1573.     public static void reverseArray(final Object[] array) {
  1574.         Objects.requireNonNull(array, "array");
  1575.         int i = 0;
  1576.         int j = array.length - 1;
  1577.         Object tmp;

  1578.         while (j > i) {
  1579.             tmp = array[j];
  1580.             array[j] = array[i];
  1581.             array[i] = tmp;
  1582.             j--;
  1583.             i++;
  1584.         }
  1585.     }

  1586.     /**
  1587.      * Selects all elements from input collection which match the given
  1588.      * predicate into an output collection.
  1589.      * <p>
  1590.      * A {@code null} predicate matches no elements.
  1591.      * </p>
  1592.      *
  1593.      * @param <O>  the type of object the {@link Iterable} contains
  1594.      * @param inputCollection  the collection to get the input from, may not be null
  1595.      * @param predicate  the predicate to use, may be null
  1596.      * @return the elements matching the predicate (new list)
  1597.      */
  1598.     public static <O> Collection<O> select(final Iterable<? extends O> inputCollection,
  1599.                                            final Predicate<? super O> predicate) {
  1600.         int size = 0;
  1601.         if (null != inputCollection) {
  1602.             size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
  1603.         }
  1604.         final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
  1605.         return select(inputCollection, predicate, answer);
  1606.     }

  1607.     /**
  1608.      * Selects all elements from input collection which match the given
  1609.      * predicate and adds them to outputCollection.
  1610.      * <p>
  1611.      * If the input collection or predicate is null, there is no change to the
  1612.      * output collection.
  1613.      * </p>
  1614.      *
  1615.      * @param <O>  the type of object the {@link Iterable} contains
  1616.      * @param <R>  the type of the output {@link Collection}
  1617.      * @param inputCollection  the collection to get the input from, may be null
  1618.      * @param predicate  the predicate to use, may be null
  1619.      * @param outputCollection  the collection to output into, may not be null if the inputCollection
  1620.      *   and predicate or not null
  1621.      * @return the outputCollection
  1622.      */
  1623.     public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
  1624.             final Predicate<? super O> predicate, final R outputCollection) {

  1625.         if (inputCollection != null && predicate != null) {
  1626.             for (final O item : inputCollection) {
  1627.                 if (predicate.test(item)) {
  1628.                     outputCollection.add(item);
  1629.                 }
  1630.             }
  1631.         }
  1632.         return outputCollection;
  1633.     }

  1634.     /**
  1635.      * Selects all elements from inputCollection into an output and rejected collection,
  1636.      * based on the evaluation of the given predicate.
  1637.      * <p>
  1638.      * Elements matching the predicate are added to the {@code outputCollection},
  1639.      * all other elements are added to the {@code rejectedCollection}.
  1640.      * </p>
  1641.      * <p>
  1642.      * If the input predicate is {@code null}, no elements are added to
  1643.      * {@code outputCollection} or {@code rejectedCollection}.
  1644.      * </p>
  1645.      * <p>
  1646.      * Note: calling the method is equivalent to the following code snippet:
  1647.      * </p>
  1648.      * <pre>
  1649.      *   select(inputCollection, predicate, outputCollection);
  1650.      *   selectRejected(inputCollection, predicate, rejectedCollection);
  1651.      * </pre>
  1652.      *
  1653.      * @param <O>  the type of object the {@link Iterable} contains
  1654.      * @param <R>  the type of the output {@link Collection}
  1655.      * @param inputCollection  the collection to get the input from, may be null
  1656.      * @param predicate  the predicate to use, may be null
  1657.      * @param outputCollection  the collection to output selected elements into, may not be null if the
  1658.      *   inputCollection and predicate are not null
  1659.      * @param rejectedCollection  the collection to output rejected elements into, may not be null if the
  1660.      *   inputCollection or predicate are not null
  1661.      * @return the outputCollection
  1662.      * @since 4.1
  1663.      */
  1664.     public static <O, R extends Collection<? super O>> R select(final Iterable<? extends O> inputCollection,
  1665.             final Predicate<? super O> predicate, final R outputCollection, final R rejectedCollection) {

  1666.         if (inputCollection != null && predicate != null) {
  1667.             for (final O element : inputCollection) {
  1668.                 if (predicate.test(element)) {
  1669.                     outputCollection.add(element);
  1670.                 } else {
  1671.                     rejectedCollection.add(element);
  1672.                 }
  1673.             }
  1674.         }
  1675.         return outputCollection;
  1676.     }

  1677.     /**
  1678.      * Selects all elements from inputCollection which don't match the given
  1679.      * predicate into an output collection.
  1680.      * <p>
  1681.      * If the input predicate is {@code null}, the result is an empty
  1682.      * list.
  1683.      * </p>
  1684.      *
  1685.      * @param <O>  the type of object the {@link Iterable} contains
  1686.      * @param inputCollection  the collection to get the input from, may not be null
  1687.      * @param predicate  the predicate to use, may be null
  1688.      * @return the elements <strong>not</strong> matching the predicate (new list)
  1689.      */
  1690.     public static <O> Collection<O> selectRejected(final Iterable<? extends O> inputCollection,
  1691.                                                    final Predicate<? super O> predicate) {
  1692.         int size = 0;
  1693.         if (null != inputCollection) {
  1694.             size = inputCollection instanceof Collection<?> ? ((Collection<?>) inputCollection).size() : 0;
  1695.         }
  1696.         final Collection<O> answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size);
  1697.         return selectRejected(inputCollection, predicate, answer);
  1698.     }

  1699.     /**
  1700.      * Selects all elements from inputCollection which don't match the given
  1701.      * predicate and adds them to outputCollection.
  1702.      * <p>
  1703.      * If the input predicate is {@code null}, no elements are added to
  1704.      * {@code outputCollection}.
  1705.      * </p>
  1706.      *
  1707.      * @param <O>  the type of object the {@link Iterable} contains
  1708.      * @param <R>  the type of the output {@link Collection}
  1709.      * @param inputCollection  the collection to get the input from, may be null
  1710.      * @param predicate  the predicate to use, may be null
  1711.      * @param outputCollection  the collection to output into, may not be null if the inputCollection
  1712.      *   and predicate or not null
  1713.      * @return outputCollection
  1714.      */
  1715.     public static <O, R extends Collection<? super O>> R selectRejected(final Iterable<? extends O> inputCollection,
  1716.             final Predicate<? super O> predicate, final R outputCollection) {

  1717.         if (inputCollection != null && predicate != null) {
  1718.             for (final O item : inputCollection) {
  1719.                 if (!predicate.test(item)) {
  1720.                     outputCollection.add(item);
  1721.                 }
  1722.             }
  1723.         }
  1724.         return outputCollection;
  1725.     }

  1726.     /**
  1727.      * Gets the size of the collection/iterator specified.
  1728.      * <p>
  1729.      * This method can handles objects as follows
  1730.      * </p>
  1731.      * <ul>
  1732.      * <li>Collection - the collection size
  1733.      * <li>Map - the map size
  1734.      * <li>Array - the array size
  1735.      * <li>Iterator - the number of elements remaining in the iterator
  1736.      * <li>Enumeration - the number of elements remaining in the enumeration
  1737.      * </ul>
  1738.      *
  1739.      * @param object  the object to get the size of, may be null
  1740.      * @return the size of the specified collection or 0 if the object was null
  1741.      * @throws IllegalArgumentException thrown if object is not recognized
  1742.      * @since 3.1
  1743.      */
  1744.     public static int size(final Object object) {
  1745.         if (object == null) {
  1746.             return 0;
  1747.         }
  1748.         int total = 0;
  1749.         if (object instanceof Map<?, ?>) {
  1750.             total = ((Map<?, ?>) object).size();
  1751.         } else if (object instanceof Collection<?>) {
  1752.             total = ((Collection<?>) object).size();
  1753.         } else if (object instanceof Iterable<?>) {
  1754.             total = IterableUtils.size((Iterable<?>) object);
  1755.         } else if (object instanceof Object[]) {
  1756.             total = ((Object[]) object).length;
  1757.         } else if (object instanceof Iterator<?>) {
  1758.             total = IteratorUtils.size((Iterator<?>) object);
  1759.         } else if (object instanceof Enumeration<?>) {
  1760.             final Enumeration<?> it = (Enumeration<?>) object;
  1761.             while (it.hasMoreElements()) {
  1762.                 total++;
  1763.                 it.nextElement();
  1764.             }
  1765.         } else {
  1766.             try {
  1767.                 total = Array.getLength(object);
  1768.             } catch (final IllegalArgumentException ex) {
  1769.                 throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
  1770.             }
  1771.         }
  1772.         return total;
  1773.     }

  1774.     /**
  1775.      * Checks if the specified collection/array/iterator is empty.
  1776.      * <p>
  1777.      * This method can handles objects as follows
  1778.      * </p>
  1779.      * <ul>
  1780.      * <li>Collection - via collection isEmpty
  1781.      * <li>Map - via map isEmpty
  1782.      * <li>Array - using array size
  1783.      * <li>Iterator - via hasNext
  1784.      * <li>Enumeration - via hasMoreElements
  1785.      * </ul>
  1786.      * <p>
  1787.      * Note: This method is named to avoid clashing with
  1788.      * {@link #isEmpty(Collection)}.
  1789.      * </p>
  1790.      *
  1791.      * @param object  the object to get the size of, may be null
  1792.      * @return true if empty or null
  1793.      * @throws IllegalArgumentException thrown if object is not recognized
  1794.      * @since 3.2
  1795.      */
  1796.     public static boolean sizeIsEmpty(final Object object) {
  1797.         if (object == null) {
  1798.             return true;
  1799.         }
  1800.         if (object instanceof Collection<?>) {
  1801.             return ((Collection<?>) object).isEmpty();
  1802.         }
  1803.         if (object instanceof Iterable<?>) {
  1804.             return IterableUtils.isEmpty((Iterable<?>) object);
  1805.         }
  1806.         if (object instanceof Map<?, ?>) {
  1807.             return ((Map<?, ?>) object).isEmpty();
  1808.         }
  1809.         if (object instanceof Object[]) {
  1810.             return ((Object[]) object).length == 0;
  1811.         }
  1812.         if (object instanceof Iterator<?>) {
  1813.             return !((Iterator<?>) object).hasNext();
  1814.         }
  1815.         if (object instanceof Enumeration<?>) {
  1816.             return !((Enumeration<?>) object).hasMoreElements();
  1817.         }
  1818.         try {
  1819.             return Array.getLength(object) == 0;
  1820.         } catch (final IllegalArgumentException ex) {
  1821.             throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
  1822.         }
  1823.     }

  1824.     /**
  1825.      * Returns a new {@link Collection} containing {@code <em>a</em> - <em>b</em>}.
  1826.      * The cardinality of each element <em>e</em> in the returned {@link Collection}
  1827.      * will be the cardinality of <em>e</em> in <em>a</em> minus the cardinality
  1828.      * of <em>e</em> in <em>b</em>, or zero, whichever is greater.
  1829.      *
  1830.      * @param a  the collection to subtract from, must not be null
  1831.      * @param b  the collection to subtract, must not be null
  1832.      * @param <O> the generic type that is able to represent the types contained
  1833.      *        in both input collections.
  1834.      * @return a new collection with the results
  1835.      * @see Collection#removeAll
  1836.      */
  1837.     public static <O> Collection<O> subtract(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  1838.         final Predicate<O> p = TruePredicate.truePredicate();
  1839.         return subtract(a, b, p);
  1840.     }

  1841.     /**
  1842.      * Returns a new {@link Collection} containing <em>a</em> minus a subset of
  1843.      * <em>b</em>.  Only the elements of <em>b</em> that satisfy the predicate
  1844.      * condition, <em>p</em> are subtracted from <em>a</em>.
  1845.      *
  1846.      * <p>
  1847.      * The cardinality of each element <em>e</em> in the returned {@link Collection}
  1848.      * that satisfies the predicate condition will be the cardinality of <em>e</em> in <em>a</em>
  1849.      * minus the cardinality of <em>e</em> in <em>b</em>, or zero, whichever is greater.
  1850.      * </p>
  1851.      * <p>
  1852.      * The cardinality of each element <em>e</em> in the returned {@link Collection} that does <strong>not</strong>
  1853.      * satisfy the predicate condition will be equal to the cardinality of <em>e</em> in <em>a</em>.
  1854.      * </p>
  1855.      *
  1856.      * @param a  the collection to subtract from, must not be null
  1857.      * @param b  the collection to subtract, must not be null
  1858.      * @param p  the condition used to determine which elements of <em>b</em> are
  1859.      *        subtracted.
  1860.      * @param <O> the generic type that is able to represent the types contained
  1861.      *        in both input collections.
  1862.      * @return a new collection with the results
  1863.      * @throws NullPointerException if either collection or p is null
  1864.      * @since 4.0
  1865.      * @see Collection#removeAll
  1866.      */
  1867.     public static <O> Collection<O> subtract(final Iterable<? extends O> a,
  1868.                                              final Iterable<? extends O> b,
  1869.                                              final Predicate<O> p) {
  1870.         Objects.requireNonNull(a, "a");
  1871.         Objects.requireNonNull(b, "b");
  1872.         Objects.requireNonNull(p, "p");
  1873.         final ArrayList<O> list = new ArrayList<>();
  1874.         final HashBag<O> bag = new HashBag<>();
  1875.         for (final O element : b) {
  1876.             if (p.test(element)) {
  1877.                 bag.add(element);
  1878.             }
  1879.         }
  1880.         for (final O element : a) {
  1881.             if (!bag.remove(element, 1)) {
  1882.                 list.add(element);
  1883.             }
  1884.         }
  1885.         return list;
  1886.     }

  1887.     /**
  1888.      * Returns a synchronized collection backed by the given collection.
  1889.      * <p>
  1890.      * You must manually synchronize on the returned buffer's iterator to
  1891.      * avoid non-deterministic behavior:
  1892.      * </p>
  1893.      * <pre>
  1894.      * Collection c = CollectionUtils.synchronizedCollection(myCollection);
  1895.      * synchronized (c) {
  1896.      *     Iterator i = c.iterator();
  1897.      *     while (i.hasNext()) {
  1898.      *         process (i.next());
  1899.      *     }
  1900.      * }
  1901.      * </pre>
  1902.      * <p>
  1903.      * This method uses the implementation in the decorators subpackage.
  1904.      * </p>
  1905.      *
  1906.      * @param <C>  the type of object the {@link Collection} contains
  1907.      * @param collection  the collection to synchronize, must not be null
  1908.      * @return a synchronized collection backed by the given collection
  1909.      * @throws NullPointerException if the collection is null
  1910.      * @deprecated since 4.1, use {@link java.util.Collections#synchronizedCollection(Collection)} instead
  1911.      */
  1912.     @Deprecated
  1913.     public static <C> Collection<C> synchronizedCollection(final Collection<C> collection) {
  1914.         Objects.requireNonNull(collection, "collection");
  1915.         return SynchronizedCollection.synchronizedCollection(collection);
  1916.     }

  1917.     /**
  1918.      * Transform the collection by applying a Transformer to each element.
  1919.      * <p>
  1920.      * If the input collection or transformer is null, there is no change made.
  1921.      * </p>
  1922.      * <p>
  1923.      * This routine is best for Lists, for which set() is used to do the
  1924.      * transformations "in place." For other Collections, clear() and addAll()
  1925.      * are used to replace elements.
  1926.      * </p>
  1927.      * <p>
  1928.      * If the input collection controls its input, such as a Set, and the
  1929.      * Transformer creates duplicates (or are otherwise invalid), the collection
  1930.      * may reduce in size due to calling this method.
  1931.      * </p>
  1932.      *
  1933.      * @param <C>  the type of object the {@link Collection} contains
  1934.      * @param collection  the {@link Collection} to get the input from, may be null
  1935.      * @param transformer  the transformer to perform, may be null
  1936.      */
  1937.     public static <C> void transform(final Collection<C> collection,
  1938.                                      final Transformer<? super C, ? extends C> transformer) {

  1939.         if (collection != null && transformer != null) {
  1940.             if (collection instanceof List<?>) {
  1941.                 final List<C> list = (List<C>) collection;
  1942.                 for (final ListIterator<C> it = list.listIterator(); it.hasNext();) {
  1943.                     it.set(transformer.apply(it.next()));
  1944.                 }
  1945.             } else {
  1946.                 final Collection<C> resultCollection = collect(collection, transformer);
  1947.                 collection.clear();
  1948.                 collection.addAll(resultCollection);
  1949.             }
  1950.         }
  1951.     }

  1952.     /**
  1953.      * Returns a transformed bag backed by the given collection.
  1954.      * <p>
  1955.      * Each object is passed through the transformer as it is added to the
  1956.      * Collection. It is important not to use the original collection after invoking this
  1957.      * method, as it is a backdoor for adding untransformed objects.
  1958.      * </p>
  1959.      * <p>
  1960.      * Existing entries in the specified collection will not be transformed.
  1961.      * If you want that behavior, see {@link TransformedCollection#transformedCollection}.
  1962.      * </p>
  1963.      *
  1964.      * @param <E> the type of object the {@link Collection} contains
  1965.      * @param collection  the collection to predicate, must not be null
  1966.      * @param transformer  the transformer for the collection, must not be null
  1967.      * @return a transformed collection backed by the given collection
  1968.      * @throws NullPointerException if the collection or transformer is null
  1969.      */
  1970.     public static <E> Collection<E> transformingCollection(final Collection<E> collection,
  1971.             final Transformer<? super E, ? extends E> transformer) {
  1972.         Objects.requireNonNull(collection, "collection");
  1973.         Objects.requireNonNull(transformer, "transformer");
  1974.         return TransformedCollection.transformingCollection(collection, transformer);
  1975.     }

  1976.     /**
  1977.      * Returns a {@link Collection} containing the union of the given
  1978.      * {@link Iterable}s.
  1979.      * <p>
  1980.      * The cardinality of each element in the returned {@link Collection} will
  1981.      * be equal to the maximum of the cardinality of that element in the two
  1982.      * given {@link Iterable}s.
  1983.      * </p>
  1984.      *
  1985.      * @param a the first collection, must not be null
  1986.      * @param b the second collection, must not be null
  1987.      * @param <O> the generic type that is able to represent the types contained
  1988.      *        in both input collections.
  1989.      * @return the union of the two collections
  1990.      * @throws NullPointerException if either collection is null
  1991.      * @see Collection#addAll
  1992.      */
  1993.     public static <O> Collection<O> union(final Iterable<? extends O> a, final Iterable<? extends O> b) {
  1994.         Objects.requireNonNull(a, "a");
  1995.         Objects.requireNonNull(b, "b");
  1996.         final SetOperationCardinalityHelper<O> helper = new SetOperationCardinalityHelper<>(a, b);
  1997.         for (final O obj : helper) {
  1998.             helper.setCardinality(obj, helper.max(obj));
  1999.         }
  2000.         return helper.list();
  2001.     }

  2002.     /**
  2003.      * Returns an unmodifiable collection backed by the given collection.
  2004.      * <p>
  2005.      * This method uses the implementation in the decorators subpackage.
  2006.      * </p>
  2007.      *
  2008.      * @param <C>  the type of object the {@link Collection} contains
  2009.      * @param collection  the collection to make unmodifiable, must not be null
  2010.      * @return an unmodifiable collection backed by the given collection
  2011.      * @throws NullPointerException if the collection is null
  2012.      * @deprecated since 4.1, use {@link java.util.Collections#unmodifiableCollection(Collection)} instead
  2013.      */
  2014.     @Deprecated
  2015.     public static <C> Collection<C> unmodifiableCollection(final Collection<? extends C> collection) {
  2016.         Objects.requireNonNull(collection, "collection");
  2017.         return UnmodifiableCollection.unmodifiableCollection(collection);
  2018.     }

  2019.     /**
  2020.      * Don't allow instances.
  2021.      */
  2022.     private CollectionUtils() {
  2023.         // empty
  2024.     }
  2025. }