ListUtils.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.util.AbstractList;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Objects;

  26. import org.apache.commons.collections4.bag.HashBag;
  27. import org.apache.commons.collections4.functors.DefaultEquator;
  28. import org.apache.commons.collections4.list.FixedSizeList;
  29. import org.apache.commons.collections4.list.LazyList;
  30. import org.apache.commons.collections4.list.PredicatedList;
  31. import org.apache.commons.collections4.list.TransformedList;
  32. import org.apache.commons.collections4.list.UnmodifiableList;
  33. import org.apache.commons.collections4.sequence.CommandVisitor;
  34. import org.apache.commons.collections4.sequence.EditScript;
  35. import org.apache.commons.collections4.sequence.SequencesComparator;

  36. /**
  37.  * Provides utility methods and decorators for {@link List} instances.
  38.  *
  39.  * @since 1.0
  40.  */
  41. public class ListUtils {

  42.     /**
  43.      * A simple wrapper to use a CharSequence as List.
  44.      */
  45.     private static final class CharSequenceAsList extends AbstractList<Character> {
  46.         private final CharSequence sequence;

  47.         CharSequenceAsList(final CharSequence sequence) {
  48.             this.sequence = sequence;
  49.         }

  50.         @Override
  51.         public Character get(final int index) {
  52.             return Character.valueOf(sequence.charAt(index));
  53.         }

  54.         @Override
  55.         public int size() {
  56.             return sequence.length();
  57.         }
  58.     }

  59.     /**
  60.      * A helper class used to construct the longest common subsequence.
  61.      */
  62.     private static final class LcsVisitor<E> implements CommandVisitor<E> {
  63.         private final ArrayList<E> sequence;

  64.         LcsVisitor() {
  65.             sequence = new ArrayList<>();
  66.         }

  67.         public List<E> getSubSequence() {
  68.             return sequence;
  69.         }

  70.         @Override
  71.         public void visitDeleteCommand(final E object) {
  72.             // noop
  73.         }

  74.         @Override
  75.         public void visitInsertCommand(final E object) {
  76.             // noop
  77.         }

  78.         @Override
  79.         public void visitKeepCommand(final E object) {
  80.             sequence.add(object);
  81.         }
  82.     }

  83.     /**
  84.      * Provides a partition view on a {@link List}.
  85.      * @since 4.0
  86.      */
  87.     private static final class Partition<T> extends AbstractList<List<T>> {
  88.         private final List<T> list;
  89.         private final int size;

  90.         private Partition(final List<T> list, final int size) {
  91.             this.list = list;
  92.             this.size = size;
  93.         }

  94.         @Override
  95.         public List<T> get(final int index) {
  96.             final int listSize = size();
  97.             if (index < 0) {
  98.                 throw new IndexOutOfBoundsException("Index " + index + " must not be negative");
  99.             }
  100.             if (index >= listSize) {
  101.                 throw new IndexOutOfBoundsException("Index " + index + " must be less than size " +
  102.                                                     listSize);
  103.             }
  104.             final int start = index * size;
  105.             final int end = Math.min(start + size, list.size());
  106.             return list.subList(start, end);
  107.         }

  108.         @Override
  109.         public boolean isEmpty() {
  110.             return list.isEmpty();
  111.         }

  112.         @Override
  113.         public int size() {
  114.             return (int) Math.ceil((double) list.size() / (double) size);
  115.         }
  116.     }

  117.     /**
  118.      * Returns either the passed in list, or if the list is {@code null},
  119.      * the value of {@code defaultList}.
  120.      *
  121.      * @param <T> the element type
  122.      * @param list  the list, possibly {@code null}
  123.      * @param defaultList  the returned values if list is {@code null}
  124.      * @return an empty list if the argument is {@code null}
  125.      * @since 4.0
  126.      */
  127.     public static <T> List<T> defaultIfNull(final List<T> list, final List<T> defaultList) {
  128.         return list == null ? defaultList : list;
  129.     }

  130.     /**
  131.      * Returns an immutable empty list if the argument is {@code null},
  132.      * or the argument itself otherwise.
  133.      *
  134.      * @param <T> the element type
  135.      * @param list the list, possibly {@code null}
  136.      * @return an empty list if the argument is {@code null}
  137.      */
  138.     public static <T> List<T> emptyIfNull(final List<T> list) {
  139.         return list == null ? Collections.<T>emptyList() : list;
  140.     }

  141.     /**
  142.      * Returns a fixed-sized list backed by the given list.
  143.      * Elements may not be added or removed from the returned list, but
  144.      * existing elements can be changed (for instance, via the
  145.      * {@link List#set(int, Object)} method).
  146.      *
  147.      * @param <E>  the element type
  148.      * @param list  the list whose size to fix, must not be null
  149.      * @return a fixed-size list backed by that list
  150.      * @throws NullPointerException  if the List is null
  151.      */
  152.     public static <E> List<E> fixedSizeList(final List<E> list) {
  153.         return FixedSizeList.fixedSizeList(list);
  154.     }

  155.     /**
  156.      * Gets the first element of a list.
  157.      * <p>
  158.      * Shorthand for {@code list.get(0)}
  159.      * </p>
  160.      *
  161.      * @param <T> The list type.
  162.      * @param list The list.
  163.      * @return the first element of a list.
  164.      * @see List#get(int)
  165.      * @since 4.5.0-M1
  166.      */
  167.     public static <T> T getFirst(final List<T> list) {
  168.         return Objects.requireNonNull(list, "list").get(0);
  169.     }

  170.     /**
  171.      * Gets the last element of a list.
  172.      * <p>
  173.      * Shorthand for {@code list.get(list.size() - 1)}
  174.      * </p>
  175.      *
  176.      * @param <T> The list type.
  177.      * @param list The list.
  178.      * @return the last element of a list.
  179.      * @see List#get(int)
  180.      * @since 4.5.0-M1
  181.      */
  182.     public static <T> T getLast(final List<T> list) {
  183.         return Objects.requireNonNull(list, "list").get(list.size() - 1);
  184.     }

  185.     /**
  186.      * Generates a hash code using the algorithm specified in
  187.      * {@link java.util.List#hashCode()}.
  188.      * <p>
  189.      * This method is useful for implementing {@code List} when you cannot
  190.      * extend AbstractList. The method takes Collection instances to enable other
  191.      * collection types to use the List implementation algorithm.
  192.      * </p>
  193.      *
  194.      * @see java.util.List#hashCode()
  195.      * @param list  the list to generate the hashCode for, may be null
  196.      * @return the hash code
  197.      */
  198.     public static int hashCodeForList(final Collection<?> list) {
  199.         if (list == null) {
  200.             return 0;
  201.         }
  202.         int hashCode = 1;

  203.         for (final Object obj : list) {
  204.             hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
  205.         }
  206.         return hashCode;
  207.     }

  208.     /**
  209.      * Finds the first index in the given List which matches the given predicate.
  210.      * <p>
  211.      * If the input List or predicate is null, or no element of the List
  212.      * matches the predicate, -1 is returned.
  213.      * </p>
  214.      *
  215.      * @param <E>  the element type
  216.      * @param list the List to search, may be null
  217.      * @param predicate  the predicate to use, may be null
  218.      * @return the first index of an Object in the List which matches the predicate or -1 if none could be found
  219.      */
  220.     public static <E> int indexOf(final List<E> list, final Predicate<E> predicate) {
  221.         if (list != null && predicate != null) {
  222.             for (int i = 0; i < list.size(); i++) {
  223.                 final E item = list.get(i);
  224.                 if (predicate.test(item)) {
  225.                     return i;
  226.                 }
  227.             }
  228.         }
  229.         return CollectionUtils.INDEX_NOT_FOUND;
  230.     }

  231.     /**
  232.      * Returns a new list containing all elements that are contained in
  233.      * both given lists.
  234.      *
  235.      * @param <E> the element type
  236.      * @param list1  the first list
  237.      * @param list2  the second list
  238.      * @return  the intersection of those two lists
  239.      * @throws NullPointerException if either list is null
  240.      */
  241.     public static <E> List<E> intersection(final List<? extends E> list1, final List<? extends E> list2) {
  242.         final List<E> result = new ArrayList<>();

  243.         List<? extends E> smaller = list1;
  244.         List<? extends E> larger = list2;
  245.         if (list1.size() > list2.size()) {
  246.             smaller = list2;
  247.             larger = list1;
  248.         }

  249.         final HashSet<E> hashSet = new HashSet<>(smaller);

  250.         for (final E e : larger) {
  251.             if (hashSet.contains(e)) {
  252.                 result.add(e);
  253.                 hashSet.remove(e);
  254.             }
  255.         }
  256.         return result;
  257.     }

  258.     /**
  259.      * Tests two lists for value-equality as per the equality contract in
  260.      * {@link java.util.List#equals(Object)}.
  261.      * <p>
  262.      * This method is useful for implementing {@code List} when you cannot
  263.      * extend AbstractList. The method takes Collection instances to enable other
  264.      * collection types to use the List implementation algorithm.
  265.      * </p>
  266.      * <p>
  267.      * The relevant text (slightly paraphrased as this is a static method) is:
  268.      * </p>
  269.      * <blockquote>
  270.      * Compares the two list objects for equality.  Returns
  271.      * {@code true} if and only if both
  272.      * lists have the same size, and all corresponding pairs of elements in
  273.      * the two lists are <em>equal</em>.  (Two elements {@code e1} and
  274.      * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
  275.      * e1.equals(e2))}.)  In other words, two lists are defined to be
  276.      * equal if they contain the same elements in the same order.  This
  277.      * definition ensures that the equals method works properly across
  278.      * different implementations of the {@code List} interface.
  279.      * </blockquote>
  280.      * <p>
  281.      * <strong>Note:</strong> The behavior of this method is undefined if the lists are
  282.      * modified during the equals comparison.
  283.      * </p>
  284.      *
  285.      * @see java.util.List
  286.      * @param list1  the first list, may be null
  287.      * @param list2  the second list, may be null
  288.      * @return whether the lists are equal by value comparison
  289.      */
  290.     public static boolean isEqualList(final Collection<?> list1, final Collection<?> list2) {
  291.         if (list1 == list2) {
  292.             return true;
  293.         }
  294.         if (list1 == null || list2 == null || list1.size() != list2.size()) {
  295.             return false;
  296.         }

  297.         final Iterator<?> it1 = list1.iterator();
  298.         final Iterator<?> it2 = list2.iterator();

  299.         while (it1.hasNext() && it2.hasNext()) {
  300.             final Object obj1 = it1.next();
  301.             final Object obj2 = it2.next();

  302.             if (!Objects.equals(obj1, obj2)) {
  303.                 return false;
  304.             }
  305.         }

  306.         return !(it1.hasNext() || it2.hasNext());
  307.     }

  308.     /**
  309.      * Returns a "lazy" list whose elements will be created on demand.
  310.      * <p>
  311.      * When the index passed to the returned list's {@link List#get(int) get}
  312.      * method is greater than the list's size, then the factory will be used
  313.      * to create a new object and that object will be inserted at that index.
  314.      * </p>
  315.      * <p>
  316.      * For instance:
  317.      * </p>
  318.      * <pre>
  319.      * Factory&lt;Date&gt; factory = new Factory&lt;Date&gt;() {
  320.      *     public Date create() {
  321.      *         return new Date();
  322.      *     }
  323.      * }
  324.      * List&lt;Date&gt; lazy = ListUtils.lazyList(new ArrayList&lt;Date&gt;(), factory);
  325.      * Date date = lazy.get(3);
  326.      * </pre>
  327.      * <p>
  328.      * After the above code is executed, {@code date} will refer to
  329.      * a new {@code Date} instance. Furthermore, that {@code Date}
  330.      * instance is the fourth element in the list.  The first, second,
  331.      * and third element are all set to {@code null}.
  332.      * </p>
  333.      *
  334.      * @param <E> the element type
  335.      * @param list  the list to make lazy, must not be null
  336.      * @param factory  the factory for creating new objects, must not be null
  337.      * @return a lazy list backed by the given list
  338.      * @throws NullPointerException if the List or Factory is null
  339.      */
  340.     public static <E> List<E> lazyList(final List<E> list, final Factory<? extends E> factory) {
  341.         return LazyList.lazyList(list, factory);
  342.     }

  343.     /**
  344.      * Returns a "lazy" list whose elements will be created on demand.
  345.      * <p>
  346.      * When the index passed to the returned list's {@link List#get(int) get}
  347.      * method is greater than the list's size, then the transformer will be used
  348.      * to create a new object and that object will be inserted at that index.
  349.      * </p>
  350.      * <p>
  351.      * For instance:
  352.      * </p>
  353.      * <pre>
  354.      * List&lt;Integer&gt; hours = Arrays.asList(7, 5, 8, 2);
  355.      * Transformer&lt;Integer,Date&gt; transformer = input -&gt; LocalDateTime.now().withHour(hours.get(input));
  356.      * List&lt;LocalDateTime&gt; lazy = ListUtils.lazyList(new ArrayList&lt;LocalDateTime&gt;(), transformer);
  357.      * Date date = lazy.get(3);
  358.      * </pre>
  359.      * <p>
  360.      * After the above code is executed, {@code date} will refer to
  361.      * a new {@code Date} instance. Furthermore, that {@code Date}
  362.      * instance is the fourth element in the list.  The first, second,
  363.      * and third element are all set to {@code null}.
  364.      * </p>
  365.      *
  366.      * @param <E> the element type
  367.      * @param list  the list to make lazy, must not be null
  368.      * @param transformer  the transformer for creating new objects, must not be null
  369.      * @return a lazy list backed by the given list
  370.      * @throws NullPointerException if the List or Transformer is null
  371.      */
  372.     public static <E> List<E> lazyList(final List<E> list, final Transformer<Integer, ? extends E> transformer) {
  373.         return LazyList.lazyList(list, transformer);
  374.     }

  375.     /**
  376.      * Returns the longest common subsequence (LCS) of two {@link CharSequence} objects.
  377.      * <p>
  378.      * This is a convenience method for using {@link #longestCommonSubsequence(List, List)}
  379.      * with {@link CharSequence} instances.
  380.      * </p>
  381.      *
  382.      * @param charSequenceA  the first sequence
  383.      * @param charSequenceB  the second sequence
  384.      * @return the longest common subsequence as {@link String}
  385.      * @throws NullPointerException if either sequence is {@code null}
  386.      * @since 4.0
  387.      */
  388.     public static String longestCommonSubsequence(final CharSequence charSequenceA, final CharSequence charSequenceB) {
  389.         Objects.requireNonNull(charSequenceA, "charSequenceA");
  390.         Objects.requireNonNull(charSequenceB, "charSequenceB");
  391.         final List<Character> lcs = longestCommonSubsequence(new CharSequenceAsList(charSequenceA),
  392.                 new CharSequenceAsList(charSequenceB));
  393.         final StringBuilder sb = new StringBuilder();
  394.         for (final Character ch : lcs) {
  395.             sb.append(ch);
  396.         }
  397.         return sb.toString();
  398.     }

  399.     /**
  400.      * Returns the longest common subsequence (LCS) of two sequences (lists).
  401.      *
  402.      * @param <E>  the element type
  403.      * @param a  the first list
  404.      * @param b  the second list
  405.      * @return the longest common subsequence
  406.      * @throws NullPointerException if either list is {@code null}
  407.      * @since 4.0
  408.      */
  409.     public static <E> List<E> longestCommonSubsequence(final List<E> a, final List<E> b) {
  410.         return longestCommonSubsequence(a, b, DefaultEquator.defaultEquator());
  411.     }

  412.     /**
  413.      * Returns the longest common subsequence (LCS) of two sequences (lists).
  414.      *
  415.      * @param <E>  the element type
  416.      * @param listA  the first list
  417.      * @param listB  the second list
  418.      * @param equator  the equator used to test object equality
  419.      * @return the longest common subsequence
  420.      * @throws NullPointerException if either list or the equator is {@code null}
  421.      * @since 4.0
  422.      */
  423.     public static <E> List<E> longestCommonSubsequence(final List<E> listA, final List<E> listB,
  424.                                                        final Equator<? super E> equator) {
  425.         Objects.requireNonNull(listA, "listA");
  426.         Objects.requireNonNull(listB, "listB");
  427.         Objects.requireNonNull(equator, "equator");

  428.         final SequencesComparator<E> comparator = new SequencesComparator<>(listA, listB, equator);
  429.         final EditScript<E> script = comparator.getScript();
  430.         final LcsVisitor<E> visitor = new LcsVisitor<>();
  431.         script.visit(visitor);
  432.         return visitor.getSubSequence();
  433.     }

  434.     /**
  435.      * Returns consecutive {@link List#subList(int, int) sublists} of a
  436.      * list, each of the same size (the final list may be smaller). For example,
  437.      * partitioning a list containing {@code [a, b, c, d, e]} with a partition
  438.      * size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
  439.      * two inner lists of three and two elements, all in the original order.
  440.      * <p>
  441.      * The outer list is unmodifiable, but reflects the latest state of the
  442.      * source list. The inner lists are sublist views of the original list,
  443.      * produced on demand using {@link List#subList(int, int)}, and are subject
  444.      * to all the usual caveats about modification as explained in that API.
  445.      * </p>
  446.      * <p>
  447.      * Adapted from https://github.com/google/guava
  448.      * </p>
  449.      *
  450.      * @param <T> the element type
  451.      * @param list  the list to return consecutive sublists of
  452.      * @param size  the desired size of each sublist (the last may be smaller)
  453.      * @return a list of consecutive sublists
  454.      * @throws NullPointerException if list is null
  455.      * @throws IllegalArgumentException if size is not strictly positive
  456.      * @since 4.0
  457.      */
  458.     public static <T> List<List<T>> partition(final List<T> list, final int size) {
  459.         Objects.requireNonNull(list, "list");
  460.         if (size <= 0) {
  461.             throw new IllegalArgumentException("Size must be greater than 0");
  462.         }
  463.         return new Partition<>(list, size);
  464.     }

  465.     /**
  466.      * Returns a predicated (validating) list backed by the given list.
  467.      * <p>
  468.      * Only objects that pass the test in the given predicate can be added to the list.
  469.      * Trying to add an invalid object results in an IllegalArgumentException.
  470.      * It is important not to use the original list after invoking this method,
  471.      * as it is a backdoor for adding invalid objects.
  472.      * </p>
  473.      *
  474.      * @param <E> the element type
  475.      * @param list  the list to predicate, must not be null
  476.      * @param predicate  the predicate for the list, must not be null
  477.      * @return a predicated list backed by the given list
  478.      * @throws NullPointerException if the List or Predicate is null
  479.      */
  480.     public static <E> List<E> predicatedList(final List<E> list, final Predicate<E> predicate) {
  481.         return PredicatedList.predicatedList(list, predicate);
  482.     }

  483.     /**
  484.      * Removes the elements in {@code remove} from {@code collection}. That is, this
  485.      * method returns a list containing all the elements in {@code collection}
  486.      * that are not in {@code remove}. The cardinality of an element {@code e}
  487.      * in the returned collection is the same as the cardinality of {@code e}
  488.      * in {@code collection} unless {@code remove} contains {@code e}, in which
  489.      * case the cardinality is zero. This method is useful if you do not wish to modify
  490.      * {@code collection} and thus cannot call {@code collection.removeAll(remove);}.
  491.      * <p>
  492.      * This implementation iterates over {@code collection}, checking each element in
  493.      * turn to see if it's contained in {@code remove}. If it's not contained, it's added
  494.      * to the returned list. As a consequence, it is advised to use a collection type for
  495.      * {@code remove} that provides a fast (for example O(1)) implementation of
  496.      * {@link Collection#contains(Object)}.
  497.      * </p>
  498.      *
  499.      * @param <E>  the element type
  500.      * @param collection  the collection from which items are removed (in the returned collection)
  501.      * @param remove  the items to be removed from the returned {@code collection}
  502.      * @return a {@code List} containing all the elements of {@code c} except
  503.      * any elements that also occur in {@code remove}.
  504.      * @throws NullPointerException if either parameter is null
  505.      * @since 3.2
  506.      */
  507.     public static <E> List<E> removeAll(final Collection<E> collection, final Collection<?> remove) {
  508.         Objects.requireNonNull(collection, "collection");
  509.         Objects.requireNonNull(remove, "remove");
  510.         final List<E> list = new ArrayList<>();
  511.         for (final E obj : collection) {
  512.             if (!remove.contains(obj)) {
  513.                 list.add(obj);
  514.             }
  515.         }
  516.         return list;
  517.     }

  518.     /**
  519.      * Returns a List containing all the elements in {@code collection}
  520.      * that are also in {@code retain}. The cardinality of an element {@code e}
  521.      * in the returned list is the same as the cardinality of {@code e}
  522.      * in {@code collection} unless {@code retain} does not contain {@code e}, in which
  523.      * case the cardinality is zero. This method is useful if you do not wish to modify
  524.      * the collection {@code c} and thus cannot call {@code collection.retainAll(retain);}.
  525.      * <p>
  526.      * This implementation iterates over {@code collection}, checking each element in
  527.      * turn to see if it's contained in {@code retain}. If it's contained, it's added
  528.      * to the returned list. As a consequence, it is advised to use a collection type for
  529.      * {@code retain} that provides a fast (for example O(1)) implementation of
  530.      * {@link Collection#contains(Object)}.
  531.      * </p>
  532.      *
  533.      * @param <E>  the element type
  534.      * @param collection  the collection whose contents are the target of the #retailAll operation
  535.      * @param retain  the collection containing the elements to be retained in the returned collection
  536.      * @return a {@code List} containing all the elements of {@code c}
  537.      * that occur at least once in {@code retain}.
  538.      * @throws NullPointerException if either parameter is null
  539.      * @since 3.2
  540.      */
  541.     public static <E> List<E> retainAll(final Collection<E> collection, final Collection<?> retain) {
  542.         final List<E> list = new ArrayList<>(Math.min(collection.size(), retain.size()));

  543.         for (final E obj : collection) {
  544.             if (retain.contains(obj)) {
  545.                 list.add(obj);
  546.             }
  547.         }
  548.         return list;
  549.     }

  550.     /**
  551.      * Selects all elements from input collection which match the given
  552.      * predicate into an output list.
  553.      * <p>
  554.      * A {@code null} predicate matches no elements.
  555.      * </p>
  556.      *
  557.      * @param <E> the element type
  558.      * @param inputCollection  the collection to get the input from, may not be null
  559.      * @param predicate  the predicate to use, may be null
  560.      * @return the elements matching the predicate (new list)
  561.      * @throws NullPointerException if the input list is null
  562.      * @since 4.0
  563.      * @see CollectionUtils#select(Iterable, Predicate)
  564.      */
  565.     public static <E> List<E> select(final Collection<? extends E> inputCollection,
  566.             final Predicate<? super E> predicate) {
  567.         return CollectionUtils.select(inputCollection, predicate, new ArrayList<>(inputCollection.size()));
  568.     }

  569.     /**
  570.      * Selects all elements from inputCollection which don't match the given
  571.      * predicate into an output collection.
  572.      * <p>
  573.      * If the input predicate is {@code null}, the result is an empty list.
  574.      * </p>
  575.      *
  576.      * @param <E> the element type
  577.      * @param inputCollection the collection to get the input from, may not be null
  578.      * @param predicate the predicate to use, may be null
  579.      * @return the elements <strong>not</strong> matching the predicate (new list)
  580.      * @throws NullPointerException if the input collection is null
  581.      * @since 4.0
  582.      * @see CollectionUtils#selectRejected(Iterable, Predicate)
  583.      */
  584.     public static <E> List<E> selectRejected(final Collection<? extends E> inputCollection,
  585.             final Predicate<? super E> predicate) {
  586.         return CollectionUtils.selectRejected(inputCollection, predicate, new ArrayList<>(inputCollection.size()));
  587.     }

  588.     /**
  589.      * Subtracts all elements in the second list from the first list,
  590.      * placing the results in a new list.
  591.      * <p>
  592.      * This differs from {@link List#removeAll(Collection)} in that
  593.      * cardinality is respected; if <Code>list1</Code> contains two
  594.      * occurrences of <Code>null</Code> and <Code>list2</Code> only
  595.      * contains one occurrence, then the returned list will still contain
  596.      * one occurrence.
  597.      * </p>
  598.      *
  599.      * @param <E> the element type
  600.      * @param list1  the list to subtract from
  601.      * @param list2  the list to subtract
  602.      * @return a new list containing the results
  603.      * @throws NullPointerException if either list is null
  604.      */
  605.     public static <E> List<E> subtract(final List<E> list1, final List<? extends E> list2) {
  606.         final ArrayList<E> result = new ArrayList<>();
  607.         final HashBag<E> bag = new HashBag<>(list2);
  608.         for (final E e : list1) {
  609.             if (!bag.remove(e, 1)) {
  610.                 result.add(e);
  611.             }
  612.         }
  613.         return result;
  614.     }

  615.     /**
  616.      * Returns the sum of the given lists.  This is their intersection
  617.      * subtracted from their union.
  618.      *
  619.      * @param <E> the element type
  620.      * @param list1  the first list
  621.      * @param list2  the second list
  622.      * @return  a new list containing the sum of those lists
  623.      * @throws NullPointerException if either list is null
  624.      */
  625.     public static <E> List<E> sum(final List<? extends E> list1, final List<? extends E> list2) {
  626.         return subtract(union(list1, list2), intersection(list1, list2));
  627.     }

  628.     /**
  629.      * Returns a synchronized list backed by the given list.
  630.      * <p>
  631.      * You must manually synchronize on the returned list's iterator to
  632.      * avoid non-deterministic behavior:
  633.      * </p>
  634.      * <pre>
  635.      * List list = ListUtils.synchronizedList(myList);
  636.      * synchronized (list) {
  637.      *     Iterator i = list.iterator();
  638.      *     while (i.hasNext()) {
  639.      *         process (i.next());
  640.      *     }
  641.      * }
  642.      * </pre>
  643.      * <p>
  644.      * This method is just a wrapper for {@link Collections#synchronizedList(List)}.
  645.      * </p>
  646.      *
  647.      * @param <E> the element type
  648.      * @param list  the list to synchronize, must not be null
  649.      * @return a synchronized list backed by the given list
  650.      * @throws NullPointerException if the list is null
  651.      */
  652.     public static <E> List<E> synchronizedList(final List<E> list) {
  653.         return Collections.synchronizedList(list);
  654.     }

  655.     /**
  656.      * Returns a transformed list backed by the given list.
  657.      * <p>
  658.      * This method returns a new list (decorating the specified list) that
  659.      * will transform any new entries added to it.
  660.      * Existing entries in the specified list will not be transformed.
  661.      * </p>
  662.      * <p>
  663.      * Each object is passed through the transformer as it is added to the
  664.      * List. It is important not to use the original list after invoking this
  665.      * method, as it is a backdoor for adding untransformed objects.
  666.      * </p>
  667.      * <p>
  668.      * Existing entries in the specified list will not be transformed.
  669.      * If you want that behavior, see {@link TransformedList#transformedList}.
  670.      * </p>
  671.      *
  672.      * @param <E> the element type
  673.      * @param list  the list to predicate, must not be null
  674.      * @param transformer  the transformer for the list, must not be null
  675.      * @return a transformed list backed by the given list
  676.      * @throws NullPointerException if the List or Transformer is null
  677.      */
  678.     public static <E> List<E> transformedList(final List<E> list,
  679.                                               final Transformer<? super E, ? extends E> transformer) {
  680.         return TransformedList.transformingList(list, transformer);
  681.     }

  682.     /**
  683.      * Returns a new list containing the second list appended to the
  684.      * first list.  The {@link List#addAll(Collection)} operation is
  685.      * used to append the two given lists into a new list.
  686.      *
  687.      * @param <E> the element type
  688.      * @param list1  the first list
  689.      * @param list2  the second list
  690.      * @return a new list containing the union of those lists
  691.      * @throws NullPointerException if either list is null
  692.      */
  693.     public static <E> List<E> union(final List<? extends E> list1, final List<? extends E> list2) {
  694.         final ArrayList<E> result = new ArrayList<>(list1.size() + list2.size());
  695.         result.addAll(list1);
  696.         result.addAll(list2);
  697.         return result;
  698.     }

  699.     /**
  700.      * Returns an unmodifiable list backed by the given list.
  701.      * <p>
  702.      * This method uses the implementation in the decorators subpackage.
  703.      * </p>
  704.      *
  705.      * @param <E>  the element type
  706.      * @param list  the list to make unmodifiable, must not be null
  707.      * @return an unmodifiable list backed by the given list
  708.      * @throws NullPointerException if the list is null
  709.      */
  710.     public static <E> List<E> unmodifiableList(final List<? extends E> list) {
  711.         return UnmodifiableList.unmodifiableList(list);
  712.     }

  713.     /**
  714.      * Don't allow instances.
  715.      */
  716.     private ListUtils() {
  717.         // empty
  718.     }

  719. }