001/*
002 * Copyright (C) 2016 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import java.util.Comparator;
024import java.util.Iterator;
025import org.checkerframework.checker.nullness.compatqual.NullableDecl;
026
027/**
028 * Provides static methods for working with {@link Comparator} instances. For many other helpful
029 * comparator utilities, see either {@code Comparator} itself (for Java 8 or later), or {@code
030 * com.google.common.collect.Ordering} (otherwise).
031 *
032 * <h3>Relationship to {@code Ordering}</h3>
033 *
034 * <p>In light of the significant enhancements to {@code Comparator} in Java 8, the overwhelming
035 * majority of usages of {@code Ordering} can be written using only built-in JDK APIs. This class is
036 * intended to "fill the gap" and provide those features of {@code Ordering} not already provided by
037 * the JDK.
038 *
039 * @since 21.0
040 * @author Louis Wasserman
041 */
042@Beta
043@GwtCompatible
044public final class Comparators {
045  private Comparators() {}
046
047  /**
048   * Returns a new comparator which sorts iterables by comparing corresponding elements pairwise
049   * until a nonzero result is found; imposes "dictionary order." If the end of one iterable is
050   * reached, but not the other, the shorter iterable is considered to be less than the longer one.
051   * For example, a lexicographical natural ordering over integers considers {@code [] < [1] < [1,
052   * 1] < [1, 2] < [2]}.
053   *
054   * <p>Note that {@code Collections.reverseOrder(lexicographical(comparator))} is not equivalent to
055   * {@code lexicographical(Collections.reverseOrder(comparator))} (consider how each would order
056   * {@code [1]} and {@code [1, 1]}).
057   */
058  // Note: 90% of the time we don't add type parameters or wildcards that serve only to "tweak" the
059  // desired return type. However, *nested* generics introduce a special class of problems that we
060  // think tip it over into being worthwhile.
061  public static <T, S extends T> Comparator<Iterable<S>> lexicographical(Comparator<T> comparator) {
062    return new LexicographicalOrdering<S>(checkNotNull(comparator));
063  }
064
065  /**
066   * Returns {@code true} if each element in {@code iterable} after the first is greater than or
067   * equal to the element that preceded it, according to the specified comparator. Note that this is
068   * always true when the iterable has fewer than two elements.
069   */
070  public static <T> boolean isInOrder(Iterable<? extends T> iterable, Comparator<T> comparator) {
071    checkNotNull(comparator);
072    Iterator<? extends T> it = iterable.iterator();
073    if (it.hasNext()) {
074      T prev = it.next();
075      while (it.hasNext()) {
076        T next = it.next();
077        if (comparator.compare(prev, next) > 0) {
078          return false;
079        }
080        prev = next;
081      }
082    }
083    return true;
084  }
085
086  /**
087   * Returns {@code true} if each element in {@code iterable} after the first is <i>strictly</i>
088   * greater than the element that preceded it, according to the specified comparator. Note that
089   * this is always true when the iterable has fewer than two elements.
090   */
091  public static <T> boolean isInStrictOrder(
092      Iterable<? extends T> iterable, Comparator<T> comparator) {
093    checkNotNull(comparator);
094    Iterator<? extends T> it = iterable.iterator();
095    if (it.hasNext()) {
096      T prev = it.next();
097      while (it.hasNext()) {
098        T next = it.next();
099        if (comparator.compare(prev, next) >= 0) {
100          return false;
101        }
102        prev = next;
103      }
104    }
105    return true;
106  }
107
108  /**
109   * Returns the minimum of the two values. If the values compare as 0, the first is returned.
110   *
111   * <p>The recommended solution for finding the {@code minimum} of some values depends on the type
112   * of your data and the number of elements you have. Read more in the Guava User Guide article on
113   * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code
114   * Comparators}</a>.
115   *
116   * @param a first value to compare, returned if less than or equal to b.
117   * @param b second value to compare.
118   * @throws ClassCastException if the parameters are not <i>mutually comparable</i>.
119   * @since 30.0
120   */
121  @Beta
122  public static <T extends Comparable<? super T>> T min(T a, T b) {
123    return (a.compareTo(b) <= 0) ? a : b;
124  }
125
126  /**
127   * Returns the minimum of the two values, according to the given comparator. If the values compare
128   * as equal, the first is returned.
129   *
130   * <p>The recommended solution for finding the {@code minimum} of some values depends on the type
131   * of your data and the number of elements you have. Read more in the Guava User Guide article on
132   * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code
133   * Comparators}</a>.
134   *
135   * @param a first value to compare, returned if less than or equal to b
136   * @param b second value to compare.
137   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> using the given
138   *     comparator.
139   * @since 30.0
140   */
141  @Beta
142  public static <T> T min(@NullableDecl T a, @NullableDecl T b, Comparator<T> comparator) {
143    return (comparator.compare(a, b) <= 0) ? a : b;
144  }
145
146  /**
147   * Returns the maximum of the two values. If the values compare as 0, the first is returned.
148   *
149   * <p>The recommended solution for finding the {@code maximum} of some values depends on the type
150   * of your data and the number of elements you have. Read more in the Guava User Guide article on
151   * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code
152   * Comparators}</a>.
153   *
154   * @param a first value to compare, returned if greater than or equal to b.
155   * @param b second value to compare.
156   * @throws ClassCastException if the parameters are not <i>mutually comparable</i>.
157   * @since 30.0
158   */
159  @Beta
160  public static <T extends Comparable<? super T>> T max(T a, T b) {
161    return (a.compareTo(b) >= 0) ? a : b;
162  }
163
164  /**
165   * Returns the maximum of the two values, according to the given comparator. If the values compare
166   * as equal, the first is returned.
167   *
168   * <p>The recommended solution for finding the {@code maximum} of some values depends on the type
169   * of your data and the number of elements you have. Read more in the Guava User Guide article on
170   * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code
171   * Comparators}</a>.
172   *
173   * @param a first value to compare, returned if greater than or equal to b.
174   * @param b second value to compare.
175   * @throws ClassCastException if the parameters are not <i>mutually comparable</i> using the given
176   *     comparator.
177   * @since 30.0
178   */
179  @Beta
180  public static <T> T max(@NullableDecl T a, @NullableDecl T b, Comparator<T> comparator) {
181    return (comparator.compare(a, b) >= 0) ? a : b;
182  }
183}