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