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 {@code 033 * 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. 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 @Beta 064 public static <T, S extends T> Comparator<Iterable<S>> lexicographical(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 @Beta 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 @Beta 096 public static <T> 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 22.0 132 */ 133 public static <T> Collector<T, ?, List<T>> least(int k, Comparator<? super T> comparator) { 134 checkNonnegative(k, "k"); 135 checkNotNull(comparator); 136 return Collector.of( 137 () -> TopKSelector.<T>least(k, comparator), 138 TopKSelector::offer, 139 TopKSelector::combine, 140 TopKSelector::topK, 141 Collector.Characteristics.UNORDERED); 142 } 143 144 /** 145 * Returns a {@code Collector} that returns the {@code k} greatest (relative to the specified 146 * {@code Comparator}) input elements, in descending order, as an unmodifiable {@code List}. Ties 147 * are broken arbitrarily. 148 * 149 * <p>For example: 150 * 151 * <pre>{@code 152 * Stream.of("foo", "quux", "banana", "elephant") 153 * .collect(greatest(2, comparingInt(String::length))) 154 * // returns {"elephant", "banana"} 155 * }</pre> 156 * 157 * <p>This {@code Collector} uses O(k) memory and takes expected time O(n) (worst-case O(n log 158 * k)), as opposed to e.g. {@code Stream.sorted(comparator.reversed()).limit(k)}, which currently 159 * takes O(n log n) time and O(n) space. 160 * 161 * @throws IllegalArgumentException if {@code k < 0} 162 * @since 22.0 163 */ 164 public static <T> Collector<T, ?, List<T>> greatest(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 174 */ 175 @Beta 176 public static <T> Comparator<Optional<T>> emptiesFirst(Comparator<? super T> valueComparator) { 177 checkNotNull(valueComparator); 178 return Comparator.comparing(o -> o.orElse(null), 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 187 */ 188 @Beta 189 public static <T> Comparator<Optional<T>> emptiesLast(Comparator<? super T> valueComparator) { 190 checkNotNull(valueComparator); 191 return Comparator.comparing(o -> o.orElse(null), Comparator.nullsLast(valueComparator)); 192 } 193}