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; 020import static com.google.common.collect.CollectPreconditions.checkNonnegative; 021 022import com.google.common.annotations.GwtCompatible; 023import java.util.Comparator; 024import java.util.Iterator; 025import java.util.List; 026import java.util.Optional; 027import java.util.stream.Collector; 028import javax.annotation.CheckForNull; 029import org.checkerframework.checker.nullness.qual.Nullable; 030 031/** 032 * Provides static methods for working with {@link Comparator} instances. For many other helpful 033 * comparator utilities, see either {@code Comparator} itself (for Java 8+), or {@code 034 * com.google.common.collect.Ordering} (otherwise). 035 * 036 * <h3>Relationship to {@code Ordering}</h3> 037 * 038 * <p>In light of the significant enhancements to {@code Comparator} in Java 8, the overwhelming 039 * majority of usages of {@code Ordering} can be written using only built-in JDK APIs. This class is 040 * intended to "fill the gap" and provide those features of {@code Ordering} not already provided by 041 * the JDK. 042 * 043 * @since 21.0 044 * @author Louis Wasserman 045 */ 046@GwtCompatible 047@ElementTypesAreNonnullByDefault 048public final class Comparators { 049 private Comparators() {} 050 051 /** 052 * Returns a new comparator which sorts iterables by comparing corresponding elements pairwise 053 * until a nonzero result is found; imposes "dictionary order." If the end of one iterable is 054 * reached, but not the other, the shorter iterable is considered to be less than the longer one. 055 * For example, a lexicographical natural ordering over integers considers {@code [] < [1] < [1, 056 * 1] < [1, 2] < [2]}. 057 * 058 * <p>Note that {@code Collections.reverseOrder(lexicographical(comparator))} is not equivalent to 059 * {@code lexicographical(Collections.reverseOrder(comparator))} (consider how each would order 060 * {@code [1]} and {@code [1, 1]}). 061 */ 062 // Note: 90% of the time we don't add type parameters or wildcards that serve only to "tweak" the 063 // desired return type. However, *nested* generics introduce a special class of problems that we 064 // think tip it over into being worthwhile. 065 public static <T extends @Nullable Object, S extends T> Comparator<Iterable<S>> lexicographical( 066 Comparator<T> comparator) { 067 return new LexicographicalOrdering<S>(checkNotNull(comparator)); 068 } 069 070 /** 071 * Returns {@code true} if each element in {@code iterable} after the first is greater than or 072 * equal to the element that preceded it, according to the specified comparator. Note that this is 073 * always true when the iterable has fewer than two elements. 074 */ 075 public static <T extends @Nullable Object> boolean isInOrder( 076 Iterable<? extends T> iterable, Comparator<T> comparator) { 077 checkNotNull(comparator); 078 Iterator<? extends T> it = iterable.iterator(); 079 if (it.hasNext()) { 080 T prev = it.next(); 081 while (it.hasNext()) { 082 T next = it.next(); 083 if (comparator.compare(prev, next) > 0) { 084 return false; 085 } 086 prev = next; 087 } 088 } 089 return true; 090 } 091 092 /** 093 * Returns {@code true} if each element in {@code iterable} after the first is <i>strictly</i> 094 * greater than the element that preceded it, according to the specified comparator. Note that 095 * this is always true when the iterable has fewer than two elements. 096 */ 097 public static <T extends @Nullable Object> boolean isInStrictOrder( 098 Iterable<? extends T> iterable, Comparator<T> comparator) { 099 checkNotNull(comparator); 100 Iterator<? extends T> it = iterable.iterator(); 101 if (it.hasNext()) { 102 T prev = it.next(); 103 while (it.hasNext()) { 104 T next = it.next(); 105 if (comparator.compare(prev, next) >= 0) { 106 return false; 107 } 108 prev = next; 109 } 110 } 111 return true; 112 } 113 114 /** 115 * Returns a {@code Collector} that returns the {@code k} smallest (relative to the specified 116 * {@code Comparator}) input elements, in ascending order, as an unmodifiable {@code List}. Ties 117 * are broken arbitrarily. 118 * 119 * <p>For example: 120 * 121 * <pre>{@code 122 * Stream.of("foo", "quux", "banana", "elephant") 123 * .collect(least(2, comparingInt(String::length))) 124 * // returns {"foo", "quux"} 125 * }</pre> 126 * 127 * <p>This {@code Collector} uses O(k) memory and takes expected time O(n) (worst-case O(n log 128 * k)), as opposed to e.g. {@code Stream.sorted(comparator).limit(k)}, which currently takes O(n 129 * log n) time and O(n) space. 130 * 131 * @throws IllegalArgumentException if {@code k < 0} 132 * @since 22.0 133 */ 134 public static <T extends @Nullable Object> Collector<T, ?, List<T>> least( 135 int k, Comparator<? super T> comparator) { 136 checkNonnegative(k, "k"); 137 checkNotNull(comparator); 138 return Collector.of( 139 () -> TopKSelector.<T>least(k, comparator), 140 TopKSelector::offer, 141 TopKSelector::combine, 142 TopKSelector::topK, 143 Collector.Characteristics.UNORDERED); 144 } 145 146 /** 147 * Returns a {@code Collector} that returns the {@code k} greatest (relative to the specified 148 * {@code Comparator}) input elements, in descending order, as an unmodifiable {@code List}. Ties 149 * are broken arbitrarily. 150 * 151 * <p>For example: 152 * 153 * <pre>{@code 154 * Stream.of("foo", "quux", "banana", "elephant") 155 * .collect(greatest(2, comparingInt(String::length))) 156 * // returns {"elephant", "banana"} 157 * }</pre> 158 * 159 * <p>This {@code Collector} uses O(k) memory and takes expected time O(n) (worst-case O(n log 160 * k)), as opposed to e.g. {@code Stream.sorted(comparator.reversed()).limit(k)}, which currently 161 * takes O(n log n) time and O(n) space. 162 * 163 * @throws IllegalArgumentException if {@code k < 0} 164 * @since 22.0 165 */ 166 public static <T extends @Nullable Object> Collector<T, ?, List<T>> greatest( 167 int k, Comparator<? super T> comparator) { 168 return least(k, comparator.reversed()); 169 } 170 171 /** 172 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as less 173 * than all other values, and orders the rest using {@code valueComparator} on the contained 174 * value. 175 * 176 * @since 22.0 (but only since 33.4.0 in the Android flavor) 177 */ 178 public static <T> Comparator<Optional<T>> emptiesFirst(Comparator<? super T> valueComparator) { 179 checkNotNull(valueComparator); 180 return Comparator.<Optional<T>, @Nullable T>comparing( 181 o -> orElseNull(o), Comparator.nullsFirst(valueComparator)); 182 } 183 184 /** 185 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as greater 186 * than all other values, and orders the rest using {@code valueComparator} on the contained 187 * value. 188 * 189 * @since 22.0 (but only since 33.4.0 in the Android flavor) 190 */ 191 public static <T> Comparator<Optional<T>> emptiesLast(Comparator<? super T> valueComparator) { 192 checkNotNull(valueComparator); 193 return Comparator.<Optional<T>, @Nullable T>comparing( 194 o -> orElseNull(o), Comparator.nullsLast(valueComparator)); 195 } 196 197 // For discussion of why this exists, see the Android flavor. 198 @CheckForNull 199 private static <T> T orElseNull(Optional<T> optional) { 200 return optional.orElse(null); 201 } 202 203 /** 204 * Returns the minimum of the two values. If the values compare as 0, the first is returned. 205 * 206 * <p>The recommended solution for finding the {@code minimum} of some values depends on the type 207 * of your data and the number of elements you have. Read more in the Guava User Guide article on 208 * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code 209 * Comparators}</a>. 210 * 211 * @param a first value to compare, returned if less than or equal to b. 212 * @param b second value to compare. 213 * @throws ClassCastException if the parameters are not <i>mutually comparable</i>. 214 * @since 30.0 215 */ 216 public static <T extends Comparable<? super T>> T min(T a, T b) { 217 return (a.compareTo(b) <= 0) ? a : b; 218 } 219 220 /** 221 * Returns the minimum of the two values, according to the given comparator. If the values compare 222 * as equal, the first is returned. 223 * 224 * <p>The recommended solution for finding the {@code minimum} of some values depends on the type 225 * of your data and the number of elements you have. Read more in the Guava User Guide article on 226 * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code 227 * Comparators}</a>. 228 * 229 * @param a first value to compare, returned if less than or equal to b 230 * @param b second value to compare. 231 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> using the given 232 * comparator. 233 * @since 30.0 234 */ 235 @ParametricNullness 236 public static <T extends @Nullable Object> T min( 237 @ParametricNullness T a, @ParametricNullness T b, Comparator<? super T> comparator) { 238 return (comparator.compare(a, b) <= 0) ? a : b; 239 } 240 241 /** 242 * Returns the maximum of the two values. If the values compare as 0, the first is returned. 243 * 244 * <p>The recommended solution for finding the {@code maximum} of some values depends on the type 245 * of your data and the number of elements you have. Read more in the Guava User Guide article on 246 * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code 247 * Comparators}</a>. 248 * 249 * @param a first value to compare, returned if greater than or equal to b. 250 * @param b second value to compare. 251 * @throws ClassCastException if the parameters are not <i>mutually comparable</i>. 252 * @since 30.0 253 */ 254 public static <T extends Comparable<? super T>> T max(T a, T b) { 255 return (a.compareTo(b) >= 0) ? a : b; 256 } 257 258 /** 259 * Returns the maximum of the two values, according to the given comparator. If the values compare 260 * as equal, the first is returned. 261 * 262 * <p>The recommended solution for finding the {@code maximum} of some values depends on the type 263 * of your data and the number of elements you have. Read more in the Guava User Guide article on 264 * <a href="https://github.com/google/guava/wiki/CollectionUtilitiesExplained#comparators">{@code 265 * Comparators}</a>. 266 * 267 * @param a first value to compare, returned if greater than or equal to b. 268 * @param b second value to compare. 269 * @throws ClassCastException if the parameters are not <i>mutually comparable</i> using the given 270 * comparator. 271 * @since 30.0 272 */ 273 @ParametricNullness 274 public static <T extends @Nullable Object> T max( 275 @ParametricNullness T a, @ParametricNullness T b, Comparator<? super T> comparator) { 276 return (comparator.compare(a, b) >= 0) ? a : b; 277 } 278}