    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.collections4;
    018
    019import java.util.Collection;
    020import java.util.Comparator;
    021
    022import org.apache.commons.collections4.comparators.BooleanComparator;
    023import org.apache.commons.collections4.comparators.ComparableComparator;
    024import org.apache.commons.collections4.comparators.ComparatorChain;
    025import org.apache.commons.collections4.comparators.NullComparator;
    026import org.apache.commons.collections4.comparators.ReverseComparator;
    027import org.apache.commons.collections4.comparators.TransformingComparator;
    028
    029/**
    030 * Provides convenient static utility methods for <Code>Comparator</Code>
    031 * objects.
    032 * <p>
    033 * Most of the functionality in this class can also be found in the
    034 * <code>comparators</code> package. This class merely provides a
    035 * convenient central place if you have use for more than one class
    036 * in the <code>comparators</code> subpackage.
    037 *
    038 * @since 2.1
    039 */
    040public class ComparatorUtils {
    041
    042    /**
    043     * ComparatorUtils should not normally be instantiated.
    044     */
    045    private ComparatorUtils() {}
    046
    047    /**
    048     * Comparator for natural sort order.
    049     *
    050     * @see ComparableComparator#comparableComparator()
    051     */
    052    @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation
    053    public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>comparableComparator();
    054
    055    /**
    056     * Gets a comparator that uses the natural order of the objects.
    057     *
    058     * @param <E>  the object type to compare
    059     * @return  a comparator which uses natural order
    060     */
    061    @SuppressWarnings("unchecked")
    062    public static <E extends Comparable<? super E>> Comparator<E> naturalComparator() {
    063        return NATURAL_COMPARATOR;
    064    }
    065
    066    /**
    067     * Gets a comparator that compares using an array of {@link Comparator}s, applied
    068     * in sequence until one returns not equal or the array is exhausted.
    069     *
    070     * @param <E>  the object type to compare
    071     * @param comparators  the comparators to use, not null or empty or containing nulls
    072     * @return a {@link ComparatorChain} formed from the input comparators
    073     * @throws NullPointerException if comparators array is null or contains a null
    074     * @see ComparatorChain
    075     */
    076    public static <E> Comparator<E> chainedComparator(final Comparator<E>... comparators) {
    077        final ComparatorChain<E> chain = new ComparatorChain<>();
    078        for (final Comparator<E> comparator : comparators) {
    079            if (comparator == null) {
    080                throw new NullPointerException("Comparator cannot be null");
    081            }
    082            chain.addComparator(comparator);
    083        }
    084        return chain;
    085    }
    086
    087    /**
    088     * Gets a comparator that compares using a collection of {@link Comparator}s,
    089     * applied in (default iterator) sequence until one returns not equal or the
    090     * collection is exhausted.
    091     *
    092     * @param <E>  the object type to compare
    093     * @param comparators  the comparators to use, not null or empty or containing nulls
    094     * @return a {@link ComparatorChain} formed from the input comparators
    095     * @throws NullPointerException if comparators collection is null or contains a null
    096     * @throws ClassCastException if the comparators collection contains the wrong object type
    097     * @see ComparatorChain
    098     */
    099    @SuppressWarnings("unchecked")
    100    public static <E> Comparator<E> chainedComparator(final Collection<Comparator<E>> comparators) {
    101        return chainedComparator(
    102            (Comparator<E>[]) comparators.toArray(new Comparator[comparators.size()])
    103        );
    104    }
    105
    106    /**
    107     * Gets a comparator that reverses the order of the given comparator.
    108     *
    109     * @param <E>  the object type to compare
    110     * @param comparator  the comparator to reverse
    111     * @return  a comparator that reverses the order of the input comparator
    112     * @see ReverseComparator
    113     */
    114    public static <E> Comparator<E> reversedComparator(final Comparator<E> comparator) {
    115        return new ReverseComparator<>(comparator);
    116    }
    117
    118    /**
    119     * Gets a Comparator that can sort Boolean objects.
    120     * <p>
    121     * The parameter specifies whether true or false is sorted first.
    122     * <p>
    123     * The comparator throws NullPointerException if a null value is compared.
    124     *
    125     * @param trueFirst  when <code>true</code>, sort
    126     *        <code>true</code> {@link Boolean}s before
    127     *        <code>false</code> {@link Boolean}s.
    128     * @return  a comparator that sorts booleans
    129     */
    130    public static Comparator<Boolean> booleanComparator(final boolean trueFirst) {
    131        return BooleanComparator.booleanComparator(trueFirst);
    132    }
    133
    134    /**
    135     * Gets a Comparator that controls the comparison of <code>null</code> values.
    136     * <p>
    137     * The returned comparator will consider a null value to be less than
    138     * any nonnull value, and equal to any other null value.  Two nonnull
    139     * values will be evaluated with the given comparator.
    140     *
    141     * @param <E>  the object type to compare
    142     * @param comparator the comparator that wants to allow nulls
    143     * @return  a version of that comparator that allows nulls
    144     * @see NullComparator
    145     */
    146    @SuppressWarnings("unchecked")
    147    public static <E> Comparator<E> nullLowComparator(Comparator<E> comparator) {
    148        if (comparator == null) {
    149            comparator = NATURAL_COMPARATOR;
    150        }
    151        return new NullComparator<>(comparator, false);
    152    }
    153
    154    /**
    155     * Gets a Comparator that controls the comparison of <code>null</code> values.
    156     * <p>
    157     * The returned comparator will consider a null value to be greater than
    158     * any nonnull value, and equal to any other null value.  Two nonnull
    159     * values will be evaluated with the given comparator.
    160     *
    161     * @param <E>  the object type to compare
    162     * @param comparator the comparator that wants to allow nulls
    163     * @return  a version of that comparator that allows nulls
    164     * @see NullComparator
    165     */
    166    @SuppressWarnings("unchecked")
    167    public static <E> Comparator<E> nullHighComparator(Comparator<E> comparator) {
    168        if (comparator == null) {
    169            comparator = NATURAL_COMPARATOR;
    170        }
    171        return new NullComparator<>(comparator, true);
    172    }
    173
    174    /**
    175     * Gets a Comparator that passes transformed objects to the given comparator.
    176     * <p>
    177     * Objects passed to the returned comparator will first be transformed
    178     * by the given transformer before they are compared by the given
    179     * comparator.
    180     *
    181     * @param <I>  the input object type of the transformed comparator
    182     * @param <O>  the object type of the decorated comparator
    183     * @param comparator  the sort order to use
    184     * @param transformer  the transformer to use
    185     * @return  a comparator that transforms its input objects before comparing them
    186     * @see  TransformingComparator
    187     */
    188    @SuppressWarnings("unchecked")
    189    public static <I, O> Comparator<I> transformedComparator(Comparator<O> comparator,
    190            final Transformer<? super I, ? extends O> transformer) {
    191
    192        if (comparator == null) {
    193            comparator = NATURAL_COMPARATOR;
    194        }
    195        return new TransformingComparator<>(transformer, comparator);
    196    }
    197
    198    /**
    199     * Returns the smaller of the given objects according to the given
    200     * comparator, returning the second object if the comparator
    201     * returns equal.
    202     *
    203     * @param <E>  the object type to compare
    204     * @param o1  the first object to compare
    205     * @param o2  the second object to compare
    206     * @param comparator  the sort order to use
    207     * @return  the smaller of the two objects
    208     */
    209    @SuppressWarnings("unchecked")
    210    public static <E> E min(final E o1, final E o2, Comparator<E> comparator) {
    211        if (comparator == null) {
    212            comparator = NATURAL_COMPARATOR;
    213        }
    214        final int c = comparator.compare(o1, o2);
    215        return c < 0 ? o1 : o2;
    216    }
    217
    218    /**
    219     * Returns the larger of the given objects according to the given
    220     * comparator, returning the second object if the comparator
    221     * returns equal.
    222     *
    223     * @param <E>  the object type to compare
    224     * @param o1  the first object to compare
    225     * @param o2  the second object to compare
    226     * @param comparator  the sort order to use
    227     * @return  the larger of the two objects
    228     */
    229    @SuppressWarnings("unchecked")
    230    public static <E> E max(final E o1, final E o2, Comparator<E> comparator) {
    231        if (comparator == null) {
    232            comparator = NATURAL_COMPARATOR;
    233        }
    234        final int c = comparator.compare(o1, o2);
    235        return c > 0 ? o1 : o2;
    236    }
    237
    238}