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.Beta; 023import com.google.common.annotations.GwtCompatible; 024import java.util.Comparator; 025import java.util.Iterator; 026import java.util.List; 027import java.util.Optional; 028import java.util.stream.Collector; 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 later), or 033 * {@code com.google.common.collect.Ordering} (otherwise). 034 * 035 * <h3>Relationship to {@code Ordering}</h3> 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. Because of 039 * this, and because it's awkward to have to convert comparators into {@code Ordering} instances, 040 * {@code Ordering} and its methods are planned for deletion. This class is intended to 041 * "fill the gap" and provide those features of {@code Ordering} not already provided by the JDK. 042 * 043 * @since 21.0 044 * @author Louis Wasserman 045 */ 046@Beta 047@GwtCompatible 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 056 * [] < [1] < [1, 1] < [1, 2] < [2]}. 057 * 058 * <p>Note that {@code Collections.reverseOrder(lexicographical(comparator))} is not 059 * equivalent to {@code lexicographical(Collections.reverseOrder(comparator))} (consider how each 060 * would order {@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, S extends T> Comparator<Iterable<S>> lexicographical(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 072 * is always true when the iterable has fewer than two elements. 073 */ 074 public static <T> boolean isInOrder(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> 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}. 115 * Ties are broken arbitrarily. 116 * 117 * For example: 118 * <pre> {@code 119 * 120 * Stream.of("foo", "quux", "banana", "elephant") 121 * .collect(least(2, comparingInt(String::length))) 122 * // returns {"foo", "quux"}}</pre> 123 * 124 * <p>This {@code Collector} uses O(k) memory and takes expected time O(n) 125 * (worst-case O(n log k)), as opposed to e.g. {@code Stream.sorted(comparator).limit(k)}, which 126 * currently takes O(n log n) time and O(n) space. 127 * 128 * @throws IllegalArgumentException if {@code k < 0} 129 * @since 22.0 130 */ 131 public static <T> Collector<T, ?, List<T>> least(int k, Comparator<? super T> comparator) { 132 checkNonnegative(k, "k"); 133 checkNotNull(comparator); 134 return Collector.of( 135 () -> TopKSelector.<T>least(k, comparator), 136 TopKSelector::offer, 137 TopKSelector::combine, 138 TopKSelector::topK, 139 Collector.Characteristics.UNORDERED); 140 } 141 142 /** 143 * Returns a {@code Collector} that returns the {@code k} greatest (relative to the specified 144 * {@code Comparator}) input elements, in descending order, as an unmodifiable {@code List}. 145 * Ties are broken arbitrarily. 146 * 147 * For example: 148 * <pre> {@code 149 * 150 * Stream.of("foo", "quux", "banana", "elephant") 151 * .collect(greatest(2, comparingInt(String::length))) 152 * // returns {"elephant", "banana"}}</pre> 153 * 154 * <p>This {@code Collector} uses O(k) memory and takes expected time O(n) 155 * (worst-case O(n log k)), as opposed to e.g. 156 * {@code Stream.sorted(comparator.reversed()).limit(k)}, which currently takes O(n log n) time 157 * and O(n) space. 158 * 159 * @throws IllegalArgumentException if {@code k < 0} 160 * @since 22.0 161 */ 162 public static <T> Collector<T, ?, List<T>> greatest(int k, Comparator<? super T> comparator) { 163 return least(k, comparator.reversed()); 164 } 165 166 /** 167 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as less 168 * than all other values, and orders the rest using {@code valueComparator} on the contained 169 * value. 170 * 171 * @since 22.0 172 */ 173 @Beta 174 public static <T> Comparator<Optional<T>> emptiesFirst(Comparator<T> valueComparator) { 175 checkNotNull(valueComparator); 176 return Comparator.comparing(o -> o.orElse(null), Comparator.nullsFirst(valueComparator)); 177 } 178 179 /** 180 * Returns a comparator of {@link Optional} values which treats {@link Optional#empty} as greater 181 * than all other values, and orders the rest using {@code valueComparator} on the contained 182 * value. 183 * 184 * @since 22.0 185 */ 186 @Beta 187 public static <T> Comparator<Optional<T>> emptiesLast(Comparator<T> valueComparator) { 188 checkNotNull(valueComparator); 189 return Comparator.comparing(o -> o.orElse(null), Comparator.nullsLast(valueComparator)); 190 } 191}