ComparatorUtils.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.Collection;
  19. import java.util.Comparator;
  20. import java.util.Objects;

  21. import org.apache.commons.collections4.comparators.BooleanComparator;
  22. import org.apache.commons.collections4.comparators.ComparableComparator;
  23. import org.apache.commons.collections4.comparators.ComparatorChain;
  24. import org.apache.commons.collections4.comparators.NullComparator;
  25. import org.apache.commons.collections4.comparators.ReverseComparator;
  26. import org.apache.commons.collections4.comparators.TransformingComparator;

  27. /**
  28.  * Provides convenient static utility methods for <Code>Comparator</Code>
  29.  * objects.
  30.  * <p>
  31.  * Most of the functionality in this class can also be found in the
  32.  * {@code comparators} package. This class merely provides a
  33.  * convenient central place if you have use for more than one class
  34.  * in the {@code comparators} subpackage.
  35.  * </p>
  36.  *
  37.  * @since 2.1
  38.  */
  39. public class ComparatorUtils {

  40.     @SuppressWarnings("rawtypes")
  41.     private static final Comparator[] EMPTY_COMPARATOR_ARRAY = {};

  42.     /**
  43.      * Comparator for natural sort order.
  44.      *
  45.      * @see ComparableComparator#comparableComparator()
  46.      */
  47.     @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation
  48.     public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>comparableComparator();

  49.     /**
  50.      * Gets a Comparator that can sort Boolean objects.
  51.      * <p>
  52.      * The parameter specifies whether true or false is sorted first.
  53.      * </p>
  54.      * <p>
  55.      * The comparator throws NullPointerException if a null value is compared.
  56.      * </p>
  57.      *
  58.      * @param trueFirst  when {@code true}, sort
  59.      *        {@code true} {@link Boolean}s before
  60.      *        {@code false} {@link Boolean}s.
  61.      * @return  a comparator that sorts booleans
  62.      */
  63.     public static Comparator<Boolean> booleanComparator(final boolean trueFirst) {
  64.         return BooleanComparator.booleanComparator(trueFirst);
  65.     }

  66.     /**
  67.      * Gets a comparator that compares using a collection of {@link Comparator}s,
  68.      * applied in (default iterator) sequence until one returns not equal or the
  69.      * collection is exhausted.
  70.      *
  71.      * @param <E>  the object type to compare
  72.      * @param comparators  the comparators to use, not null or empty or containing nulls
  73.      * @return a {@link ComparatorChain} formed from the input comparators
  74.      * @throws NullPointerException if comparators collection is null or contains a null
  75.      * @throws ClassCastException if the comparators collection contains the wrong object type
  76.      * @see ComparatorChain
  77.      */
  78.     @SuppressWarnings("unchecked")
  79.     public static <E> Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators) {
  80.         return chainedComparator(comparators.toArray(EMPTY_COMPARATOR_ARRAY));
  81.     }

  82.     /**
  83.      * Gets a comparator that compares using an array of {@link Comparator}s, applied
  84.      * in sequence until one returns not equal or the array is exhausted.
  85.      *
  86.      * @param <E>  the object type to compare
  87.      * @param comparators  the comparators to use, not null or empty or containing nulls
  88.      * @return a {@link ComparatorChain} formed from the input comparators
  89.      * @throws NullPointerException if comparators array is null or contains a null
  90.      * @see ComparatorChain
  91.      */
  92.     public static <E> Comparator<E> chainedComparator(final Comparator<E>... comparators) {
  93.         final ComparatorChain<E> chain = new ComparatorChain<>();
  94.         for (final Comparator<E> comparator : comparators) {
  95.             chain.addComparator(Objects.requireNonNull(comparator, "comparator"));
  96.         }
  97.         return chain;
  98.     }

  99.     /**
  100.      * Returns the largest of the given objects according to the given
  101.      * comparator, returning the second object if the comparator
  102.      * returns equal.
  103.      *
  104.      * @param <E>  the object type to compare
  105.      * @param o1  the first object to compare
  106.      * @param o2  the second object to compare
  107.      * @param comparator  the sort order to use
  108.      * @return  the larger of the two objects
  109.      */
  110.     @SuppressWarnings("unchecked")
  111.     public static <E> E max(final E o1, final E o2, Comparator<E> comparator) {
  112.         if (comparator == null) {
  113.             comparator = NATURAL_COMPARATOR;
  114.         }
  115.         final int c = comparator.compare(o1, o2);
  116.         return c > 0 ? o1 : o2;
  117.     }

  118.     /**
  119.      * Returns the smallest of the given objects according to the given
  120.      * comparator, returning the second object if the comparator
  121.      * returns equal.
  122.      *
  123.      * @param <E>  the object type to compare
  124.      * @param o1  the first object to compare
  125.      * @param o2  the second object to compare
  126.      * @param comparator  the sort order to use
  127.      * @return  the smaller of the two objects
  128.      */
  129.     @SuppressWarnings("unchecked")
  130.     public static <E> E min(final E o1, final E o2, Comparator<E> comparator) {
  131.         if (comparator == null) {
  132.             comparator = NATURAL_COMPARATOR;
  133.         }
  134.         final int c = comparator.compare(o1, o2);
  135.         return c < 0 ? o1 : o2;
  136.     }

  137.     /**
  138.      * Gets a comparator that uses the natural order of the objects.
  139.      *
  140.      * @param <E>  the object type to compare
  141.      * @return  a comparator which uses natural order
  142.      */
  143.     @SuppressWarnings("unchecked")
  144.     public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() {
  145.         return NATURAL_COMPARATOR;
  146.     }

  147.     /**
  148.      * Gets a Comparator that controls the comparison of {@code null} values.
  149.      * <p>
  150.      * The returned comparator will consider a null value to be greater than
  151.      * any nonnull value, and equal to any other null value.  Two nonnull
  152.      * values will be evaluated with the given comparator.
  153.      * </p>
  154.      *
  155.      * @param <E>  the object type to compare
  156.      * @param comparator the comparator that wants to allow nulls
  157.      * @return  a version of that comparator that allows nulls
  158.      * @see NullComparator
  159.      */
  160.     @SuppressWarnings("unchecked")
  161.     public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
  162.         if (comparator == null) {
  163.             comparator = NATURAL_COMPARATOR;
  164.         }
  165.         return new NullComparator<>(comparator, true);
  166.     }

  167.     /**
  168.      * Gets a Comparator that controls the comparison of {@code null} values.
  169.      * <p>
  170.      * The returned comparator will consider a null value to be less than
  171.      * any nonnull value, and equal to any other null value.  Two nonnull
  172.      * values will be evaluated with the given comparator.
  173.      * </p>
  174.      *
  175.      * @param <E>  the object type to compare
  176.      * @param comparator the comparator that wants to allow nulls
  177.      * @return  a version of that comparator that allows nulls
  178.      * @see NullComparator
  179.      */
  180.     @SuppressWarnings("unchecked")
  181.     public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
  182.         if (comparator == null) {
  183.             comparator = NATURAL_COMPARATOR;
  184.         }
  185.         return new NullComparator<>(comparator, false);
  186.     }

  187.     /**
  188.      * Gets a comparator that reverses the order of the given comparator.
  189.      *
  190.      * @param <E>  the object type to compare
  191.      * @param comparator  the comparator to reverse
  192.      * @return  a comparator that reverses the order of the input comparator
  193.      * @see ReverseComparator
  194.      */
  195.     public static <E> Comparator<E> reversedComparator(final Comparator<E> comparator) {
  196.         return new ReverseComparator<>(comparator);
  197.     }

  198.     /**
  199.      * Gets a Comparator that passes transformed objects to the given comparator.
  200.      * <p>
  201.      * Objects passed to the returned comparator will first be transformed
  202.      * by the given transformer before they are compared by the given
  203.      * comparator.
  204.      * </p>
  205.      *
  206.      * @param <I>  the input object type of the transformed comparator
  207.      * @param <O>  the object type of the decorated comparator
  208.      * @param comparator  the sort order to use
  209.      * @param transformer  the transformer to use
  210.      * @return  a comparator that transforms its input objects before comparing them
  211.      * @see  TransformingComparator
  212.      */
  213.     @SuppressWarnings("unchecked")
  214.     public static <I, O> Comparator<I> transformedComparator(Comparator<O> comparator,
  215.             final Transformer<? super I, ? extends O> transformer) {

  216.         if (comparator == null) {
  217.             comparator = NATURAL_COMPARATOR;
  218.         }
  219.         return new TransformingComparator<>(transformer, comparator);
  220.     }

  221.     /**
  222.      * Don't allow instances.
  223.      */
  224.     private ComparatorUtils() {
  225.         // empty
  226.     }

  227. }