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