001/* 002 * Copyright (C) 2007 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.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.base.Predicates.compose; 022import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; 023import static com.google.common.collect.CollectPreconditions.checkNonnegative; 024import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; 025import static java.util.Collections.singletonMap; 026import static java.util.Objects.requireNonNull; 027 028import com.google.common.annotations.GwtCompatible; 029import com.google.common.annotations.GwtIncompatible; 030import com.google.common.annotations.J2ktIncompatible; 031import com.google.common.base.Converter; 032import com.google.common.base.Equivalence; 033import com.google.common.base.Function; 034import com.google.common.base.Objects; 035import com.google.common.base.Preconditions; 036import com.google.common.base.Predicate; 037import com.google.common.base.Predicates; 038import com.google.common.collect.MapDifference.ValueDifference; 039import com.google.common.primitives.Ints; 040import com.google.errorprone.annotations.CanIgnoreReturnValue; 041import com.google.errorprone.annotations.concurrent.LazyInit; 042import com.google.j2objc.annotations.RetainedWith; 043import com.google.j2objc.annotations.Weak; 044import com.google.j2objc.annotations.WeakOuter; 045import java.io.Serializable; 046import java.util.AbstractCollection; 047import java.util.AbstractMap; 048import java.util.Collection; 049import java.util.Collections; 050import java.util.Comparator; 051import java.util.EnumMap; 052import java.util.Enumeration; 053import java.util.HashMap; 054import java.util.IdentityHashMap; 055import java.util.Iterator; 056import java.util.LinkedHashMap; 057import java.util.Map; 058import java.util.Map.Entry; 059import java.util.NavigableMap; 060import java.util.NavigableSet; 061import java.util.Properties; 062import java.util.Set; 063import java.util.SortedMap; 064import java.util.SortedSet; 065import java.util.Spliterator; 066import java.util.Spliterators; 067import java.util.TreeMap; 068import java.util.concurrent.ConcurrentHashMap; 069import java.util.concurrent.ConcurrentMap; 070import java.util.function.BiConsumer; 071import java.util.function.BiFunction; 072import java.util.function.BinaryOperator; 073import java.util.function.Consumer; 074import java.util.stream.Collector; 075import javax.annotation.CheckForNull; 076import org.checkerframework.checker.nullness.qual.NonNull; 077import org.checkerframework.checker.nullness.qual.Nullable; 078 079/** 080 * Static utility methods pertaining to {@link Map} instances (including instances of {@link 081 * SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets} 082 * and {@link Queues}. 083 * 084 * <p>See the Guava User Guide article on <a href= 085 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#maps">{@code Maps}</a>. 086 * 087 * @author Kevin Bourrillion 088 * @author Mike Bostock 089 * @author Isaac Shum 090 * @author Louis Wasserman 091 * @since 2.0 092 */ 093@GwtCompatible(emulated = true) 094@ElementTypesAreNonnullByDefault 095public final class Maps { 096 private Maps() {} 097 098 private enum EntryFunction implements Function<Entry<?, ?>, @Nullable Object> { 099 KEY { 100 @Override 101 @CheckForNull 102 public Object apply(Entry<?, ?> entry) { 103 return entry.getKey(); 104 } 105 }, 106 VALUE { 107 @Override 108 @CheckForNull 109 public Object apply(Entry<?, ?> entry) { 110 return entry.getValue(); 111 } 112 }; 113 } 114 115 @SuppressWarnings("unchecked") 116 static <K extends @Nullable Object> Function<Entry<K, ?>, K> keyFunction() { 117 return (Function) EntryFunction.KEY; 118 } 119 120 @SuppressWarnings("unchecked") 121 static <V extends @Nullable Object> Function<Entry<?, V>, V> valueFunction() { 122 return (Function) EntryFunction.VALUE; 123 } 124 125 static <K extends @Nullable Object, V extends @Nullable Object> Iterator<K> keyIterator( 126 Iterator<Entry<K, V>> entryIterator) { 127 return new TransformedIterator<Entry<K, V>, K>(entryIterator) { 128 @Override 129 @ParametricNullness 130 K transform(Entry<K, V> entry) { 131 return entry.getKey(); 132 } 133 }; 134 } 135 136 static <K extends @Nullable Object, V extends @Nullable Object> Iterator<V> valueIterator( 137 Iterator<Entry<K, V>> entryIterator) { 138 return new TransformedIterator<Entry<K, V>, V>(entryIterator) { 139 @Override 140 @ParametricNullness 141 V transform(Entry<K, V> entry) { 142 return entry.getValue(); 143 } 144 }; 145 } 146 147 /** 148 * Returns an immutable map instance containing the given entries. Internally, the returned map 149 * will be backed by an {@link EnumMap}. 150 * 151 * <p>The iteration order of the returned map follows the enum's iteration order, not the order in 152 * which the elements appear in the given map. 153 * 154 * @param map the map to make an immutable copy of 155 * @return an immutable map containing those entries 156 * @since 14.0 157 */ 158 @GwtCompatible(serializable = true) 159 public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap( 160 Map<K, ? extends V> map) { 161 if (map instanceof ImmutableEnumMap) { 162 @SuppressWarnings("unchecked") // safe covariant cast 163 ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map; 164 return result; 165 } 166 Iterator<? extends Entry<K, ? extends V>> entryItr = map.entrySet().iterator(); 167 if (!entryItr.hasNext()) { 168 return ImmutableMap.of(); 169 } 170 Entry<K, ? extends V> entry1 = entryItr.next(); 171 K key1 = entry1.getKey(); 172 V value1 = entry1.getValue(); 173 checkEntryNotNull(key1, value1); 174 // Do something that works for j2cl, where we can't call getDeclaredClass(): 175 EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1)); 176 while (entryItr.hasNext()) { 177 Entry<K, ? extends V> entry = entryItr.next(); 178 K key = entry.getKey(); 179 V value = entry.getValue(); 180 checkEntryNotNull(key, value); 181 enumMap.put(key, value); 182 } 183 return ImmutableEnumMap.asImmutable(enumMap); 184 } 185 186 /** 187 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys 188 * and values are the result of applying the provided mapping functions to the input elements. The 189 * resulting implementation is specialized for enum key types. The returned map and its views will 190 * iterate over keys in their enum definition order, not encounter order. 191 * 192 * <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when 193 * the collection operation is performed. (This differs from the {@code Collector} returned by 194 * {@link java.util.stream.Collectors#toMap(java.util.function.Function, 195 * java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code 196 * IllegalStateException}.) 197 * 198 * @since 21.0 199 */ 200 public static <T extends @Nullable Object, K extends Enum<K>, V> 201 Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( 202 java.util.function.Function<? super T, ? extends K> keyFunction, 203 java.util.function.Function<? super T, ? extends V> valueFunction) { 204 return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction); 205 } 206 207 /** 208 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys 209 * and values are the result of applying the provided mapping functions to the input elements. The 210 * resulting implementation is specialized for enum key types. The returned map and its views will 211 * iterate over keys in their enum definition order, not encounter order. 212 * 213 * <p>If the mapped keys contain duplicates, the values are merged using the specified merging 214 * function. 215 * 216 * @since 21.0 217 */ 218 public static <T extends @Nullable Object, K extends Enum<K>, V> 219 Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( 220 java.util.function.Function<? super T, ? extends K> keyFunction, 221 java.util.function.Function<? super T, ? extends V> valueFunction, 222 BinaryOperator<V> mergeFunction) { 223 return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction, mergeFunction); 224 } 225 226 /** 227 * Creates a <i>mutable</i>, empty {@code HashMap} instance. 228 * 229 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead. 230 * 231 * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead. 232 * 233 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 234 * use the {@code HashMap} constructor directly, taking advantage of <a 235 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 236 * syntax</a>. 237 * 238 * @return a new, empty {@code HashMap} 239 */ 240 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 241 public static <K extends @Nullable Object, V extends @Nullable Object> 242 HashMap<K, V> newHashMap() { 243 return new HashMap<>(); 244 } 245 246 /** 247 * Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as the specified map. 248 * 249 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead. 250 * 251 * <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead. 252 * 253 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 254 * use the {@code HashMap} constructor directly, taking advantage of <a 255 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 256 * syntax</a>. 257 * 258 * @param map the mappings to be placed in the new map 259 * @return a new {@code HashMap} initialized with the mappings from {@code map} 260 */ 261 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 262 public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMap( 263 Map<? extends K, ? extends V> map) { 264 return new HashMap<>(map); 265 } 266 267 /** 268 * Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i> 269 * hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, 270 * but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method 271 * isn't inadvertently <i>oversizing</i> the returned map. 272 * 273 * @param expectedSize the number of entries you expect to add to the returned map 274 * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries 275 * without resizing 276 * @throws IllegalArgumentException if {@code expectedSize} is negative 277 */ 278 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 279 public static <K extends @Nullable Object, V extends @Nullable Object> 280 HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) { 281 return new HashMap<>(capacity(expectedSize)); 282 } 283 284 /** 285 * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no 286 * larger than expectedSize and the load factor is ≥ its default (0.75). 287 */ 288 static int capacity(int expectedSize) { 289 if (expectedSize < 3) { 290 checkNonnegative(expectedSize, "expectedSize"); 291 return expectedSize + 1; 292 } 293 if (expectedSize < Ints.MAX_POWER_OF_TWO) { 294 // This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap 295 // ends up being used to compute a "threshold" size, beyond which the internal table 296 // will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where 297 // loadFactor is 0.75 by default. So with the calculation here we ensure that the 298 // threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code 299 // path when the first operation on the new map is putAll(otherMap). There, prior to 300 // https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug 301 // meant that sometimes a too-large threshold is calculated. However, this new threshold is 302 // independent of the initial capacity, except that it won't be lower than the threshold 303 // computed from that capacity. Because the internal table is only allocated on the first 304 // write, we won't see copying because of the new threshold. So it is always OK to use the 305 // calculation here. 306 return (int) Math.ceil(expectedSize / 0.75); 307 } 308 return Integer.MAX_VALUE; // any large value 309 } 310 311 /** 312 * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance. 313 * 314 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead. 315 * 316 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 317 * use the {@code LinkedHashMap} constructor directly, taking advantage of <a 318 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 319 * syntax</a>. 320 * 321 * @return a new, empty {@code LinkedHashMap} 322 */ 323 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 324 public static <K extends @Nullable Object, V extends @Nullable Object> 325 LinkedHashMap<K, V> newLinkedHashMap() { 326 return new LinkedHashMap<>(); 327 } 328 329 /** 330 * Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance with the same 331 * mappings as the specified map. 332 * 333 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead. 334 * 335 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 336 * use the {@code LinkedHashMap} constructor directly, taking advantage of <a 337 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 338 * syntax</a>. 339 * 340 * @param map the mappings to be placed in the new map 341 * @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map} 342 */ 343 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 344 public static <K extends @Nullable Object, V extends @Nullable Object> 345 LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) { 346 return new LinkedHashMap<>(map); 347 } 348 349 /** 350 * Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it 351 * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be 352 * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed 353 * that the method isn't inadvertently <i>oversizing</i> the returned map. 354 * 355 * @param expectedSize the number of entries you expect to add to the returned map 356 * @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize} 357 * entries without resizing 358 * @throws IllegalArgumentException if {@code expectedSize} is negative 359 * @since 19.0 360 */ 361 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 362 public static <K extends @Nullable Object, V extends @Nullable Object> 363 LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) { 364 return new LinkedHashMap<>(capacity(expectedSize)); 365 } 366 367 /** 368 * Creates a new empty {@link ConcurrentHashMap} instance. 369 * 370 * @since 3.0 371 */ 372 public static <K, V> ConcurrentMap<K, V> newConcurrentMap() { 373 return new ConcurrentHashMap<>(); 374 } 375 376 /** 377 * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its 378 * elements. 379 * 380 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedMap#of()} instead. 381 * 382 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 383 * use the {@code TreeMap} constructor directly, taking advantage of <a 384 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 385 * syntax</a>. 386 * 387 * @return a new, empty {@code TreeMap} 388 */ 389 @SuppressWarnings({ 390 "rawtypes", // https://github.com/google/guava/issues/989 391 "NonApiType", // acts as a direct substitute for a constructor call 392 }) 393 public static <K extends Comparable, V extends @Nullable Object> TreeMap<K, V> newTreeMap() { 394 return new TreeMap<>(); 395 } 396 397 /** 398 * Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as the specified map 399 * and using the same ordering as the specified map. 400 * 401 * <p><b>Note:</b> if mutability is not required, use {@link 402 * ImmutableSortedMap#copyOfSorted(SortedMap)} instead. 403 * 404 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 405 * use the {@code TreeMap} constructor directly, taking advantage of <a 406 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 407 * syntax</a>. 408 * 409 * @param map the sorted map whose mappings are to be placed in the new map and whose comparator 410 * is to be used to sort the new map 411 * @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the 412 * comparator of {@code map} 413 */ 414 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 415 public static <K extends @Nullable Object, V extends @Nullable Object> TreeMap<K, V> newTreeMap( 416 SortedMap<K, ? extends V> map) { 417 return new TreeMap<>(map); 418 } 419 420 /** 421 * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given comparator. 422 * 423 * <p><b>Note:</b> if mutability is not required, use {@code 424 * ImmutableSortedMap.orderedBy(comparator).build()} instead. 425 * 426 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 427 * use the {@code TreeMap} constructor directly, taking advantage of <a 428 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 429 * syntax</a>. 430 * 431 * @param comparator the comparator to sort the keys with 432 * @return a new, empty {@code TreeMap} 433 */ 434 @SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call 435 public static <C extends @Nullable Object, K extends C, V extends @Nullable Object> 436 TreeMap<K, V> newTreeMap(@CheckForNull Comparator<C> comparator) { 437 // Ideally, the extra type parameter "C" shouldn't be necessary. It is a 438 // work-around of a compiler type inference quirk that prevents the 439 // following code from being compiled: 440 // Comparator<Class<?>> comparator = null; 441 // Map<Class<? extends Throwable>, String> map = newTreeMap(comparator); 442 return new TreeMap<>(comparator); 443 } 444 445 /** 446 * Creates an {@code EnumMap} instance. 447 * 448 * @param type the key type for this map 449 * @return a new, empty {@code EnumMap} 450 */ 451 public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap( 452 Class<K> type) { 453 return new EnumMap<>(checkNotNull(type)); 454 } 455 456 /** 457 * Creates an {@code EnumMap} with the same mappings as the specified map. 458 * 459 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 460 * use the {@code EnumMap} constructor directly, taking advantage of <a 461 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 462 * syntax</a>. 463 * 464 * @param map the map from which to initialize this {@code EnumMap} 465 * @return a new {@code EnumMap} initialized with the mappings from {@code map} 466 * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains 467 * no mappings 468 */ 469 public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap( 470 Map<K, ? extends V> map) { 471 return new EnumMap<>(map); 472 } 473 474 /** 475 * Creates an {@code IdentityHashMap} instance. 476 * 477 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, 478 * use the {@code IdentityHashMap} constructor directly, taking advantage of <a 479 * href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" 480 * syntax</a>. 481 * 482 * @return a new, empty {@code IdentityHashMap} 483 */ 484 public static <K extends @Nullable Object, V extends @Nullable Object> 485 IdentityHashMap<K, V> newIdentityHashMap() { 486 return new IdentityHashMap<>(); 487 } 488 489 /** 490 * Computes the difference between two maps. This difference is an immutable snapshot of the state 491 * of the maps at the time this method is called. It will never change, even if the maps change at 492 * a later time. 493 * 494 * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps 495 * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}. 496 * 497 * <p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code 498 * left.equals(right)} instead of this method. 499 * 500 * @param left the map to treat as the "left" map for purposes of comparison 501 * @param right the map to treat as the "right" map for purposes of comparison 502 * @return the difference between the two maps 503 */ 504 public static <K extends @Nullable Object, V extends @Nullable Object> 505 MapDifference<K, V> difference( 506 Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { 507 if (left instanceof SortedMap) { 508 @SuppressWarnings("unchecked") 509 SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left; 510 return difference(sortedLeft, right); 511 } 512 return difference(left, right, Equivalence.equals()); 513 } 514 515 /** 516 * Computes the difference between two maps. This difference is an immutable snapshot of the state 517 * of the maps at the time this method is called. It will never change, even if the maps change at 518 * a later time. 519 * 520 * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps 521 * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}. 522 * 523 * @param left the map to treat as the "left" map for purposes of comparison 524 * @param right the map to treat as the "right" map for purposes of comparison 525 * @param valueEquivalence the equivalence relationship to use to compare values 526 * @return the difference between the two maps 527 * @since 10.0 528 */ 529 public static <K extends @Nullable Object, V extends @Nullable Object> 530 MapDifference<K, V> difference( 531 Map<? extends K, ? extends V> left, 532 Map<? extends K, ? extends V> right, 533 Equivalence<? super @NonNull V> valueEquivalence) { 534 Preconditions.checkNotNull(valueEquivalence); 535 536 Map<K, V> onlyOnLeft = newLinkedHashMap(); 537 Map<K, V> onlyOnRight = new LinkedHashMap<>(right); // will whittle it down 538 Map<K, V> onBoth = newLinkedHashMap(); 539 Map<K, MapDifference.ValueDifference<V>> differences = newLinkedHashMap(); 540 doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences); 541 return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences); 542 } 543 544 /** 545 * Computes the difference between two sorted maps, using the comparator of the left map, or 546 * {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This 547 * difference is an immutable snapshot of the state of the maps at the time this method is called. 548 * It will never change, even if the maps change at a later time. 549 * 550 * <p>Since this method uses {@code TreeMap} instances internally, the keys of the right map must 551 * all compare as distinct according to the comparator of the left map. 552 * 553 * <p><b>Note:</b>If you only need to know whether two sorted maps have the same mappings, call 554 * {@code left.equals(right)} instead of this method. 555 * 556 * @param left the map to treat as the "left" map for purposes of comparison 557 * @param right the map to treat as the "right" map for purposes of comparison 558 * @return the difference between the two maps 559 * @since 11.0 560 */ 561 public static <K extends @Nullable Object, V extends @Nullable Object> 562 SortedMapDifference<K, V> difference( 563 SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) { 564 checkNotNull(left); 565 checkNotNull(right); 566 Comparator<? super K> comparator = orNaturalOrder(left.comparator()); 567 SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator); 568 SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator); 569 onlyOnRight.putAll(right); // will whittle it down 570 SortedMap<K, V> onBoth = Maps.newTreeMap(comparator); 571 SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator); 572 573 doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences); 574 return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences); 575 } 576 577 private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference( 578 Map<? extends K, ? extends V> left, 579 Map<? extends K, ? extends V> right, 580 Equivalence<? super @NonNull V> valueEquivalence, 581 Map<K, V> onlyOnLeft, 582 Map<K, V> onlyOnRight, 583 Map<K, V> onBoth, 584 Map<K, MapDifference.ValueDifference<V>> differences) { 585 for (Entry<? extends K, ? extends V> entry : left.entrySet()) { 586 K leftKey = entry.getKey(); 587 V leftValue = entry.getValue(); 588 if (right.containsKey(leftKey)) { 589 /* 590 * The cast is safe because onlyOnRight contains all the keys of right. 591 * 592 * TODO(cpovirk): Consider checking onlyOnRight.containsKey instead of right.containsKey. 593 * That could change behavior if the input maps use different equivalence relations (and so 594 * a key that appears once in `right` might appear multiple times in `left`). We don't 595 * guarantee behavior in that case, anyway, and the current behavior is likely undesirable. 596 * So that's either a reason to feel free to change it or a reason to not bother thinking 597 * further about this. 598 */ 599 V rightValue = uncheckedCastNullableTToT(onlyOnRight.remove(leftKey)); 600 if (valueEquivalence.equivalent(leftValue, rightValue)) { 601 onBoth.put(leftKey, leftValue); 602 } else { 603 differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); 604 } 605 } else { 606 onlyOnLeft.put(leftKey, leftValue); 607 } 608 } 609 } 610 611 private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> unmodifiableMap( 612 Map<K, ? extends V> map) { 613 if (map instanceof SortedMap) { 614 return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map); 615 } else { 616 return Collections.unmodifiableMap(map); 617 } 618 } 619 620 static class MapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object> 621 implements MapDifference<K, V> { 622 final Map<K, V> onlyOnLeft; 623 final Map<K, V> onlyOnRight; 624 final Map<K, V> onBoth; 625 final Map<K, ValueDifference<V>> differences; 626 627 MapDifferenceImpl( 628 Map<K, V> onlyOnLeft, 629 Map<K, V> onlyOnRight, 630 Map<K, V> onBoth, 631 Map<K, ValueDifference<V>> differences) { 632 this.onlyOnLeft = unmodifiableMap(onlyOnLeft); 633 this.onlyOnRight = unmodifiableMap(onlyOnRight); 634 this.onBoth = unmodifiableMap(onBoth); 635 this.differences = unmodifiableMap(differences); 636 } 637 638 @Override 639 public boolean areEqual() { 640 return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty(); 641 } 642 643 @Override 644 public Map<K, V> entriesOnlyOnLeft() { 645 return onlyOnLeft; 646 } 647 648 @Override 649 public Map<K, V> entriesOnlyOnRight() { 650 return onlyOnRight; 651 } 652 653 @Override 654 public Map<K, V> entriesInCommon() { 655 return onBoth; 656 } 657 658 @Override 659 public Map<K, ValueDifference<V>> entriesDiffering() { 660 return differences; 661 } 662 663 @Override 664 public boolean equals(@CheckForNull Object object) { 665 if (object == this) { 666 return true; 667 } 668 if (object instanceof MapDifference) { 669 MapDifference<?, ?> other = (MapDifference<?, ?>) object; 670 return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft()) 671 && entriesOnlyOnRight().equals(other.entriesOnlyOnRight()) 672 && entriesInCommon().equals(other.entriesInCommon()) 673 && entriesDiffering().equals(other.entriesDiffering()); 674 } 675 return false; 676 } 677 678 @Override 679 public int hashCode() { 680 return Objects.hashCode( 681 entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering()); 682 } 683 684 @Override 685 public String toString() { 686 if (areEqual()) { 687 return "equal"; 688 } 689 690 StringBuilder result = new StringBuilder("not equal"); 691 if (!onlyOnLeft.isEmpty()) { 692 result.append(": only on left=").append(onlyOnLeft); 693 } 694 if (!onlyOnRight.isEmpty()) { 695 result.append(": only on right=").append(onlyOnRight); 696 } 697 if (!differences.isEmpty()) { 698 result.append(": value differences=").append(differences); 699 } 700 return result.toString(); 701 } 702 } 703 704 static class ValueDifferenceImpl<V extends @Nullable Object> 705 implements MapDifference.ValueDifference<V> { 706 @ParametricNullness private final V left; 707 @ParametricNullness private final V right; 708 709 static <V extends @Nullable Object> ValueDifference<V> create( 710 @ParametricNullness V left, @ParametricNullness V right) { 711 return new ValueDifferenceImpl<>(left, right); 712 } 713 714 private ValueDifferenceImpl(@ParametricNullness V left, @ParametricNullness V right) { 715 this.left = left; 716 this.right = right; 717 } 718 719 @Override 720 @ParametricNullness 721 public V leftValue() { 722 return left; 723 } 724 725 @Override 726 @ParametricNullness 727 public V rightValue() { 728 return right; 729 } 730 731 @Override 732 public boolean equals(@CheckForNull Object object) { 733 if (object instanceof MapDifference.ValueDifference) { 734 MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object; 735 return Objects.equal(this.left, that.leftValue()) 736 && Objects.equal(this.right, that.rightValue()); 737 } 738 return false; 739 } 740 741 @Override 742 public int hashCode() { 743 return Objects.hashCode(left, right); 744 } 745 746 @Override 747 public String toString() { 748 return "(" + left + ", " + right + ")"; 749 } 750 } 751 752 static class SortedMapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object> 753 extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> { 754 SortedMapDifferenceImpl( 755 SortedMap<K, V> onlyOnLeft, 756 SortedMap<K, V> onlyOnRight, 757 SortedMap<K, V> onBoth, 758 SortedMap<K, ValueDifference<V>> differences) { 759 super(onlyOnLeft, onlyOnRight, onBoth, differences); 760 } 761 762 @Override 763 public SortedMap<K, ValueDifference<V>> entriesDiffering() { 764 return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering(); 765 } 766 767 @Override 768 public SortedMap<K, V> entriesInCommon() { 769 return (SortedMap<K, V>) super.entriesInCommon(); 770 } 771 772 @Override 773 public SortedMap<K, V> entriesOnlyOnLeft() { 774 return (SortedMap<K, V>) super.entriesOnlyOnLeft(); 775 } 776 777 @Override 778 public SortedMap<K, V> entriesOnlyOnRight() { 779 return (SortedMap<K, V>) super.entriesOnlyOnRight(); 780 } 781 } 782 783 /** 784 * Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}. 785 * This method is an abomination of generics; the only purpose of this method is to contain the 786 * ugly type-casting in one place. 787 */ 788 @SuppressWarnings("unchecked") 789 static <E extends @Nullable Object> Comparator<? super E> orNaturalOrder( 790 @CheckForNull Comparator<? super E> comparator) { 791 if (comparator != null) { // can't use ? : because of javac bug 5080917 792 return comparator; 793 } 794 return (Comparator<E>) Ordering.natural(); 795 } 796 797 /** 798 * Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are 799 * computed on demand using {@code function}. To get an immutable <i>copy</i> instead, use {@link 800 * #toMap(Iterable, Function)}. 801 * 802 * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping 803 * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code 804 * entrySet} views of the returned map iterate in the same order as the backing set. 805 * 806 * <p>Modifications to the backing set are read through to the returned map. The returned map 807 * supports removal operations if the backing set does. Removal operations write through to the 808 * backing set. The returned map does not support put operations. 809 * 810 * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the 811 * set does not contain {@code null}, because the view cannot stop {@code null} from being added 812 * to the set. 813 * 814 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, 815 * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for 816 * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when 817 * calling methods on the resulting map view. 818 * 819 * @since 14.0 820 */ 821 public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> asMap( 822 Set<K> set, Function<? super K, V> function) { 823 return new AsMapView<>(set, function); 824 } 825 826 /** 827 * Returns a view of the sorted set as a map, mapping keys from the set according to the specified 828 * function. 829 * 830 * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping 831 * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code 832 * entrySet} views of the returned map iterate in the same order as the backing set. 833 * 834 * <p>Modifications to the backing set are read through to the returned map. The returned map 835 * supports removal operations if the backing set does. Removal operations write through to the 836 * backing set. The returned map does not support put operations. 837 * 838 * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the 839 * set does not contain {@code null}, because the view cannot stop {@code null} from being added 840 * to the set. 841 * 842 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, 843 * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for 844 * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when 845 * calling methods on the resulting map view. 846 * 847 * @since 14.0 848 */ 849 public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> asMap( 850 SortedSet<K> set, Function<? super K, V> function) { 851 return new SortedAsMapView<>(set, function); 852 } 853 854 /** 855 * Returns a view of the navigable set as a map, mapping keys from the set according to the 856 * specified function. 857 * 858 * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping 859 * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code 860 * entrySet} views of the returned map iterate in the same order as the backing set. 861 * 862 * <p>Modifications to the backing set are read through to the returned map. The returned map 863 * supports removal operations if the backing set does. Removal operations write through to the 864 * backing set. The returned map does not support put operations. 865 * 866 * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the 867 * set does not contain {@code null}, because the view cannot stop {@code null} from being added 868 * to the set. 869 * 870 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, 871 * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for 872 * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when 873 * calling methods on the resulting map view. 874 * 875 * @since 14.0 876 */ 877 @GwtIncompatible // NavigableMap 878 public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> asMap( 879 NavigableSet<K> set, Function<? super K, V> function) { 880 return new NavigableAsMapView<>(set, function); 881 } 882 883 private static class AsMapView<K extends @Nullable Object, V extends @Nullable Object> 884 extends ViewCachingAbstractMap<K, V> { 885 886 private final Set<K> set; 887 final Function<? super K, V> function; 888 889 Set<K> backingSet() { 890 return set; 891 } 892 893 AsMapView(Set<K> set, Function<? super K, V> function) { 894 this.set = checkNotNull(set); 895 this.function = checkNotNull(function); 896 } 897 898 @Override 899 public Set<K> createKeySet() { 900 return removeOnlySet(backingSet()); 901 } 902 903 @Override 904 Collection<V> createValues() { 905 return Collections2.transform(set, function); 906 } 907 908 @Override 909 public int size() { 910 return backingSet().size(); 911 } 912 913 @Override 914 public boolean containsKey(@CheckForNull Object key) { 915 return backingSet().contains(key); 916 } 917 918 @Override 919 @CheckForNull 920 public V get(@CheckForNull Object key) { 921 return getOrDefault(key, null); 922 } 923 924 @Override 925 @CheckForNull 926 public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { 927 if (Collections2.safeContains(backingSet(), key)) { 928 @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it 929 K k = (K) key; 930 return function.apply(k); 931 } else { 932 return defaultValue; 933 } 934 } 935 936 @Override 937 @CheckForNull 938 public V remove(@CheckForNull Object key) { 939 if (backingSet().remove(key)) { 940 @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it 941 K k = (K) key; 942 return function.apply(k); 943 } else { 944 return null; 945 } 946 } 947 948 @Override 949 public void clear() { 950 backingSet().clear(); 951 } 952 953 @Override 954 protected Set<Entry<K, V>> createEntrySet() { 955 @WeakOuter 956 class EntrySetImpl extends EntrySet<K, V> { 957 @Override 958 Map<K, V> map() { 959 return AsMapView.this; 960 } 961 962 @Override 963 public Iterator<Entry<K, V>> iterator() { 964 return asMapEntryIterator(backingSet(), function); 965 } 966 } 967 return new EntrySetImpl(); 968 } 969 970 @Override 971 public void forEach(BiConsumer<? super K, ? super V> action) { 972 checkNotNull(action); 973 // avoids allocation of entries 974 backingSet().forEach(k -> action.accept(k, function.apply(k))); 975 } 976 } 977 978 static <K extends @Nullable Object, V extends @Nullable Object> 979 Iterator<Entry<K, V>> asMapEntryIterator(Set<K> set, final Function<? super K, V> function) { 980 return new TransformedIterator<K, Entry<K, V>>(set.iterator()) { 981 @Override 982 Entry<K, V> transform(@ParametricNullness final K key) { 983 return immutableEntry(key, function.apply(key)); 984 } 985 }; 986 } 987 988 private static class SortedAsMapView<K extends @Nullable Object, V extends @Nullable Object> 989 extends AsMapView<K, V> implements SortedMap<K, V> { 990 991 SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) { 992 super(set, function); 993 } 994 995 @Override 996 SortedSet<K> backingSet() { 997 return (SortedSet<K>) super.backingSet(); 998 } 999 1000 @Override 1001 @CheckForNull 1002 public Comparator<? super K> comparator() { 1003 return backingSet().comparator(); 1004 } 1005 1006 @Override 1007 public Set<K> keySet() { 1008 return removeOnlySortedSet(backingSet()); 1009 } 1010 1011 @Override 1012 public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 1013 return asMap(backingSet().subSet(fromKey, toKey), function); 1014 } 1015 1016 @Override 1017 public SortedMap<K, V> headMap(@ParametricNullness K toKey) { 1018 return asMap(backingSet().headSet(toKey), function); 1019 } 1020 1021 @Override 1022 public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { 1023 return asMap(backingSet().tailSet(fromKey), function); 1024 } 1025 1026 @Override 1027 @ParametricNullness 1028 public K firstKey() { 1029 return backingSet().first(); 1030 } 1031 1032 @Override 1033 @ParametricNullness 1034 public K lastKey() { 1035 return backingSet().last(); 1036 } 1037 } 1038 1039 @GwtIncompatible // NavigableMap 1040 private static final class NavigableAsMapView< 1041 K extends @Nullable Object, V extends @Nullable Object> 1042 extends AbstractNavigableMap<K, V> { 1043 /* 1044 * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the 1045 * NavigableMap methods. 1046 */ 1047 1048 private final NavigableSet<K> set; 1049 private final Function<? super K, V> function; 1050 1051 NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) { 1052 this.set = checkNotNull(ks); 1053 this.function = checkNotNull(vFunction); 1054 } 1055 1056 @Override 1057 public NavigableMap<K, V> subMap( 1058 @ParametricNullness K fromKey, 1059 boolean fromInclusive, 1060 @ParametricNullness K toKey, 1061 boolean toInclusive) { 1062 return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); 1063 } 1064 1065 @Override 1066 public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { 1067 return asMap(set.headSet(toKey, inclusive), function); 1068 } 1069 1070 @Override 1071 public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { 1072 return asMap(set.tailSet(fromKey, inclusive), function); 1073 } 1074 1075 @Override 1076 @CheckForNull 1077 public Comparator<? super K> comparator() { 1078 return set.comparator(); 1079 } 1080 1081 @Override 1082 @CheckForNull 1083 public V get(@CheckForNull Object key) { 1084 return getOrDefault(key, null); 1085 } 1086 1087 @Override 1088 @CheckForNull 1089 public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { 1090 if (Collections2.safeContains(set, key)) { 1091 @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it 1092 K k = (K) key; 1093 return function.apply(k); 1094 } else { 1095 return defaultValue; 1096 } 1097 } 1098 1099 @Override 1100 public void clear() { 1101 set.clear(); 1102 } 1103 1104 @Override 1105 Iterator<Entry<K, V>> entryIterator() { 1106 return asMapEntryIterator(set, function); 1107 } 1108 1109 @Override 1110 Spliterator<Entry<K, V>> entrySpliterator() { 1111 return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e))); 1112 } 1113 1114 @Override 1115 public void forEach(BiConsumer<? super K, ? super V> action) { 1116 set.forEach(k -> action.accept(k, function.apply(k))); 1117 } 1118 1119 @Override 1120 Iterator<Entry<K, V>> descendingEntryIterator() { 1121 return descendingMap().entrySet().iterator(); 1122 } 1123 1124 @Override 1125 public NavigableSet<K> navigableKeySet() { 1126 return removeOnlyNavigableSet(set); 1127 } 1128 1129 @Override 1130 public int size() { 1131 return set.size(); 1132 } 1133 1134 @Override 1135 public NavigableMap<K, V> descendingMap() { 1136 return asMap(set.descendingSet(), function); 1137 } 1138 } 1139 1140 private static <E extends @Nullable Object> Set<E> removeOnlySet(final Set<E> set) { 1141 return new ForwardingSet<E>() { 1142 @Override 1143 protected Set<E> delegate() { 1144 return set; 1145 } 1146 1147 @Override 1148 public boolean add(@ParametricNullness E element) { 1149 throw new UnsupportedOperationException(); 1150 } 1151 1152 @Override 1153 public boolean addAll(Collection<? extends E> es) { 1154 throw new UnsupportedOperationException(); 1155 } 1156 }; 1157 } 1158 1159 private static <E extends @Nullable Object> SortedSet<E> removeOnlySortedSet( 1160 final SortedSet<E> set) { 1161 return new ForwardingSortedSet<E>() { 1162 @Override 1163 protected SortedSet<E> delegate() { 1164 return set; 1165 } 1166 1167 @Override 1168 public boolean add(@ParametricNullness E element) { 1169 throw new UnsupportedOperationException(); 1170 } 1171 1172 @Override 1173 public boolean addAll(Collection<? extends E> es) { 1174 throw new UnsupportedOperationException(); 1175 } 1176 1177 @Override 1178 public SortedSet<E> headSet(@ParametricNullness E toElement) { 1179 return removeOnlySortedSet(super.headSet(toElement)); 1180 } 1181 1182 @Override 1183 public SortedSet<E> subSet( 1184 @ParametricNullness E fromElement, @ParametricNullness E toElement) { 1185 return removeOnlySortedSet(super.subSet(fromElement, toElement)); 1186 } 1187 1188 @Override 1189 public SortedSet<E> tailSet(@ParametricNullness E fromElement) { 1190 return removeOnlySortedSet(super.tailSet(fromElement)); 1191 } 1192 }; 1193 } 1194 1195 @GwtIncompatible // NavigableSet 1196 private static <E extends @Nullable Object> NavigableSet<E> removeOnlyNavigableSet( 1197 final NavigableSet<E> set) { 1198 return new ForwardingNavigableSet<E>() { 1199 @Override 1200 protected NavigableSet<E> delegate() { 1201 return set; 1202 } 1203 1204 @Override 1205 public boolean add(@ParametricNullness E element) { 1206 throw new UnsupportedOperationException(); 1207 } 1208 1209 @Override 1210 public boolean addAll(Collection<? extends E> es) { 1211 throw new UnsupportedOperationException(); 1212 } 1213 1214 @Override 1215 public SortedSet<E> headSet(@ParametricNullness E toElement) { 1216 return removeOnlySortedSet(super.headSet(toElement)); 1217 } 1218 1219 @Override 1220 public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { 1221 return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); 1222 } 1223 1224 @Override 1225 public SortedSet<E> subSet( 1226 @ParametricNullness E fromElement, @ParametricNullness E toElement) { 1227 return removeOnlySortedSet(super.subSet(fromElement, toElement)); 1228 } 1229 1230 @Override 1231 public NavigableSet<E> subSet( 1232 @ParametricNullness E fromElement, 1233 boolean fromInclusive, 1234 @ParametricNullness E toElement, 1235 boolean toInclusive) { 1236 return removeOnlyNavigableSet( 1237 super.subSet(fromElement, fromInclusive, toElement, toInclusive)); 1238 } 1239 1240 @Override 1241 public SortedSet<E> tailSet(@ParametricNullness E fromElement) { 1242 return removeOnlySortedSet(super.tailSet(fromElement)); 1243 } 1244 1245 @Override 1246 public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { 1247 return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); 1248 } 1249 1250 @Override 1251 public NavigableSet<E> descendingSet() { 1252 return removeOnlyNavigableSet(super.descendingSet()); 1253 } 1254 }; 1255 } 1256 1257 /** 1258 * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value 1259 * for each key was computed by {@code valueFunction}. The map's iteration order is the order of 1260 * the first appearance of each key in {@code keys}. 1261 * 1262 * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code 1263 * valueFunction} will be applied to more than one instance of that key and, if it is, which 1264 * result will be mapped to that key in the returned map. 1265 * 1266 * <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link 1267 * Maps#asMap(Set, Function)}. 1268 * 1269 * <p><b>Note:</b> on Java 8+, it is usually better to use streams. For example: 1270 * 1271 * <pre>{@code 1272 * import static com.google.common.collect.ImmutableMap.toImmutableMap; 1273 * ... 1274 * ImmutableMap<Color, String> colorNames = 1275 * allColors.stream().collect(toImmutableMap(c -> c, c -> c.toString())); 1276 * }</pre> 1277 * 1278 * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys 1279 * and values in the map are. 1280 * 1281 * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code 1282 * valueFunction} produces {@code null} for any key 1283 * @since 14.0 1284 */ 1285 public static <K, V> ImmutableMap<K, V> toMap( 1286 Iterable<K> keys, Function<? super K, V> valueFunction) { 1287 return toMap(keys.iterator(), valueFunction); 1288 } 1289 1290 /** 1291 * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value 1292 * for each key was computed by {@code valueFunction}. The map's iteration order is the order of 1293 * the first appearance of each key in {@code keys}. 1294 * 1295 * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code 1296 * valueFunction} will be applied to more than one instance of that key and, if it is, which 1297 * result will be mapped to that key in the returned map. 1298 * 1299 * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code 1300 * valueFunction} produces {@code null} for any key 1301 * @since 14.0 1302 */ 1303 public static <K, V> ImmutableMap<K, V> toMap( 1304 Iterator<K> keys, Function<? super K, V> valueFunction) { 1305 checkNotNull(valueFunction); 1306 ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); 1307 while (keys.hasNext()) { 1308 K key = keys.next(); 1309 builder.put(key, valueFunction.apply(key)); 1310 } 1311 // Using buildKeepingLast() so as not to fail on duplicate keys 1312 return builder.buildKeepingLast(); 1313 } 1314 1315 /** 1316 * Returns a map with the given {@code values}, indexed by keys derived from those values. In 1317 * other words, each input value produces an entry in the map whose key is the result of applying 1318 * {@code keyFunction} to that value. These entries appear in the same order as the input values. 1319 * Example usage: 1320 * 1321 * <pre>{@code 1322 * Color red = new Color("red", 255, 0, 0); 1323 * ... 1324 * ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue); 1325 * 1326 * ImmutableMap<String, Color> colorForName = 1327 * uniqueIndex(allColors, c -> c.toString()); 1328 * assertThat(colorForName).containsEntry("red", red); 1329 * }</pre> 1330 * 1331 * <p>If your index may associate multiple values with each key, use {@link 1332 * Multimaps#index(Iterable, Function) Multimaps.index}. 1333 * 1334 * <p><b>Note:</b> on Java 8+, it is usually better to use streams. For example: 1335 * 1336 * <pre>{@code 1337 * import static com.google.common.collect.ImmutableMap.toImmutableMap; 1338 * ... 1339 * ImmutableMap<String, Color> colorForName = 1340 * allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c)); 1341 * }</pre> 1342 * 1343 * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys 1344 * and values in the map are. 1345 * 1346 * @param values the values to use when constructing the {@code Map} 1347 * @param keyFunction the function used to produce the key for each value 1348 * @return a map mapping the result of evaluating the function {@code keyFunction} on each value 1349 * in the input collection to that value 1350 * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one 1351 * value in the input collection 1352 * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code 1353 * keyFunction} produces {@code null} for any value 1354 */ 1355 @CanIgnoreReturnValue 1356 public static <K, V> ImmutableMap<K, V> uniqueIndex( 1357 Iterable<V> values, Function<? super V, K> keyFunction) { 1358 if (values instanceof Collection) { 1359 return uniqueIndex( 1360 values.iterator(), 1361 keyFunction, 1362 ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size())); 1363 } 1364 return uniqueIndex(values.iterator(), keyFunction); 1365 } 1366 1367 /** 1368 * Returns a map with the given {@code values}, indexed by keys derived from those values. In 1369 * other words, each input value produces an entry in the map whose key is the result of applying 1370 * {@code keyFunction} to that value. These entries appear in the same order as the input values. 1371 * Example usage: 1372 * 1373 * <pre>{@code 1374 * Color red = new Color("red", 255, 0, 0); 1375 * ... 1376 * Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator(); 1377 * 1378 * Map<String, Color> colorForName = 1379 * uniqueIndex(allColors, toStringFunction()); 1380 * assertThat(colorForName).containsEntry("red", red); 1381 * }</pre> 1382 * 1383 * <p>If your index may associate multiple values with each key, use {@link 1384 * Multimaps#index(Iterator, Function) Multimaps.index}. 1385 * 1386 * @param values the values to use when constructing the {@code Map} 1387 * @param keyFunction the function used to produce the key for each value 1388 * @return a map mapping the result of evaluating the function {@code keyFunction} on each value 1389 * in the input collection to that value 1390 * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one 1391 * value in the input collection 1392 * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code 1393 * keyFunction} produces {@code null} for any value 1394 * @since 10.0 1395 */ 1396 @CanIgnoreReturnValue 1397 public static <K, V> ImmutableMap<K, V> uniqueIndex( 1398 Iterator<V> values, Function<? super V, K> keyFunction) { 1399 return uniqueIndex(values, keyFunction, ImmutableMap.builder()); 1400 } 1401 1402 private static <K, V> ImmutableMap<K, V> uniqueIndex( 1403 Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) { 1404 checkNotNull(keyFunction); 1405 while (values.hasNext()) { 1406 V value = values.next(); 1407 builder.put(keyFunction.apply(value), value); 1408 } 1409 try { 1410 return builder.buildOrThrow(); 1411 } catch (IllegalArgumentException duplicateKeys) { 1412 throw new IllegalArgumentException( 1413 duplicateKeys.getMessage() 1414 + ". To index multiple values under a key, use Multimaps.index."); 1415 } 1416 } 1417 1418 /** 1419 * Creates an {@code ImmutableMap<String, String>} from a {@code Properties} instance. Properties 1420 * normally derive from {@code Map<Object, Object>}, but they typically contain strings, which is 1421 * awkward. This method lets you get a plain-old-{@code Map} out of a {@code Properties}. 1422 * 1423 * @param properties a {@code Properties} object to be converted 1424 * @return an immutable map containing all the entries in {@code properties} 1425 * @throws ClassCastException if any key in {@code properties} is not a {@code String} 1426 * @throws NullPointerException if any key or value in {@code properties} is null 1427 */ 1428 @J2ktIncompatible 1429 @GwtIncompatible // java.util.Properties 1430 public static ImmutableMap<String, String> fromProperties(Properties properties) { 1431 ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); 1432 1433 for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) { 1434 /* 1435 * requireNonNull is safe because propertyNames contains only non-null elements. 1436 * 1437 * Accordingly, we have it annotated as returning `Enumeration<? extends Object>` in our 1438 * prototype checker's JDK. However, the checker still sees the return type as plain 1439 * `Enumeration<?>`, probably because of one of the following two bugs (and maybe those two 1440 * bugs are themselves just symptoms of the same underlying problem): 1441 * 1442 * https://github.com/typetools/checker-framework/issues/3030 1443 * 1444 * https://github.com/typetools/checker-framework/issues/3236 1445 */ 1446 String key = (String) requireNonNull(e.nextElement()); 1447 /* 1448 * requireNonNull is safe because the key came from propertyNames... 1449 * 1450 * ...except that it's possible for users to insert a string key with a non-string value, and 1451 * in that case, getProperty *will* return null. 1452 * 1453 * TODO(b/192002623): Handle that case: Either: 1454 * 1455 * - Skip non-string keys and values entirely, as proposed in the linked bug. 1456 * 1457 * - Throw ClassCastException instead of NullPointerException, as documented in the current 1458 * Javadoc. (Note that we can't necessarily "just" change our call to `getProperty` to `get` 1459 * because `get` does not consult the default properties.) 1460 */ 1461 builder.put(key, requireNonNull(properties.getProperty(key))); 1462 } 1463 1464 return builder.buildOrThrow(); 1465 } 1466 1467 /** 1468 * Returns an immutable map entry with the specified key and value. The {@link Entry#setValue} 1469 * operation throws an {@link UnsupportedOperationException}. 1470 * 1471 * <p>The returned entry is serializable. 1472 * 1473 * <p><b>Java 9 users:</b> consider using {@code java.util.Map.entry(key, value)} if the key and 1474 * value are non-null and the entry does not need to be serializable. 1475 * 1476 * @param key the key to be associated with the returned entry 1477 * @param value the value to be associated with the returned entry 1478 */ 1479 @GwtCompatible(serializable = true) 1480 public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> immutableEntry( 1481 @ParametricNullness K key, @ParametricNullness V value) { 1482 return new ImmutableEntry<>(key, value); 1483 } 1484 1485 /** 1486 * Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue} 1487 * operation throws an {@link UnsupportedOperationException}, as do any operations that would 1488 * modify the returned set. 1489 * 1490 * @param entrySet the entries for which to return an unmodifiable view 1491 * @return an unmodifiable view of the entries 1492 */ 1493 static <K extends @Nullable Object, V extends @Nullable Object> 1494 Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) { 1495 return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet)); 1496 } 1497 1498 /** 1499 * Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation 1500 * throws an {@link UnsupportedOperationException}. This also has the side effect of redefining 1501 * {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation 1502 * of equals. 1503 * 1504 * @param entry the entry for which to return an unmodifiable view 1505 * @return an unmodifiable view of the entry 1506 */ 1507 static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> unmodifiableEntry( 1508 final Entry<? extends K, ? extends V> entry) { 1509 checkNotNull(entry); 1510 return new AbstractMapEntry<K, V>() { 1511 @Override 1512 @ParametricNullness 1513 public K getKey() { 1514 return entry.getKey(); 1515 } 1516 1517 @Override 1518 @ParametricNullness 1519 public V getValue() { 1520 return entry.getValue(); 1521 } 1522 }; 1523 } 1524 1525 static <K extends @Nullable Object, V extends @Nullable Object> 1526 UnmodifiableIterator<Entry<K, V>> unmodifiableEntryIterator( 1527 final Iterator<Entry<K, V>> entryIterator) { 1528 return new UnmodifiableIterator<Entry<K, V>>() { 1529 @Override 1530 public boolean hasNext() { 1531 return entryIterator.hasNext(); 1532 } 1533 1534 @Override 1535 public Entry<K, V> next() { 1536 return unmodifiableEntry(entryIterator.next()); 1537 } 1538 }; 1539 } 1540 1541 /** The implementation of {@link Multimaps#unmodifiableEntries}. */ 1542 static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object> 1543 extends ForwardingCollection<Entry<K, V>> { 1544 private final Collection<Entry<K, V>> entries; 1545 1546 UnmodifiableEntries(Collection<Entry<K, V>> entries) { 1547 this.entries = entries; 1548 } 1549 1550 @Override 1551 protected Collection<Entry<K, V>> delegate() { 1552 return entries; 1553 } 1554 1555 @Override 1556 public Iterator<Entry<K, V>> iterator() { 1557 return unmodifiableEntryIterator(entries.iterator()); 1558 } 1559 1560 // See java.util.Collections.UnmodifiableEntrySet for details on attacks. 1561 1562 @Override 1563 public @Nullable Object[] toArray() { 1564 /* 1565 * standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can 1566 * be used with collections that may contain null. This collection never contains nulls, so we 1567 * could return `Object[]`. But this class is private and J2KT cannot change return types in 1568 * overrides, so we declare `@Nullable Object[]` as the return type. 1569 */ 1570 return standardToArray(); 1571 } 1572 1573 @Override 1574 @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations 1575 public <T extends @Nullable Object> T[] toArray(T[] array) { 1576 return standardToArray(array); 1577 } 1578 } 1579 1580 /** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */ 1581 static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object> 1582 extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> { 1583 UnmodifiableEntrySet(Set<Entry<K, V>> entries) { 1584 super(entries); 1585 } 1586 1587 // See java.util.Collections.UnmodifiableEntrySet for details on attacks. 1588 1589 @Override 1590 public boolean equals(@CheckForNull Object object) { 1591 return Sets.equalsImpl(this, object); 1592 } 1593 1594 @Override 1595 public int hashCode() { 1596 return Sets.hashCodeImpl(this); 1597 } 1598 } 1599 1600 /** 1601 * Returns a {@link Converter} that converts values using {@link BiMap#get bimap.get()}, and whose 1602 * inverse view converts values using {@link BiMap#inverse bimap.inverse()}{@code .get()}. 1603 * 1604 * <p>To use a plain {@link Map} as a {@link Function}, see {@link 1605 * com.google.common.base.Functions#forMap(Map)} or {@link 1606 * com.google.common.base.Functions#forMap(Map, Object)}. 1607 * 1608 * @since 16.0 1609 */ 1610 public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) { 1611 return new BiMapConverter<>(bimap); 1612 } 1613 1614 private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable { 1615 private final BiMap<A, B> bimap; 1616 1617 BiMapConverter(BiMap<A, B> bimap) { 1618 this.bimap = checkNotNull(bimap); 1619 } 1620 1621 @Override 1622 protected B doForward(A a) { 1623 return convert(bimap, a); 1624 } 1625 1626 @Override 1627 protected A doBackward(B b) { 1628 return convert(bimap.inverse(), b); 1629 } 1630 1631 private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) { 1632 Y output = bimap.get(input); 1633 checkArgument(output != null, "No non-null mapping present for input: %s", input); 1634 return output; 1635 } 1636 1637 @Override 1638 public boolean equals(@CheckForNull Object object) { 1639 if (object instanceof BiMapConverter) { 1640 BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object; 1641 return this.bimap.equals(that.bimap); 1642 } 1643 return false; 1644 } 1645 1646 @Override 1647 public int hashCode() { 1648 return bimap.hashCode(); 1649 } 1650 1651 // There's really no good way to implement toString() without printing the entire BiMap, right? 1652 @Override 1653 public String toString() { 1654 return "Maps.asConverter(" + bimap + ")"; 1655 } 1656 1657 private static final long serialVersionUID = 0L; 1658 } 1659 1660 /** 1661 * Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee 1662 * serial access, it is critical that <b>all</b> access to the backing bimap is accomplished 1663 * through the returned bimap. 1664 * 1665 * <p>It is imperative that the user manually synchronize on the returned map when accessing any 1666 * of its collection views: 1667 * 1668 * <pre>{@code 1669 * BiMap<Long, String> map = Maps.synchronizedBiMap( 1670 * HashBiMap.<Long, String>create()); 1671 * ... 1672 * Set<Long> set = map.keySet(); // Needn't be in synchronized block 1673 * ... 1674 * synchronized (map) { // Synchronizing on map, not set! 1675 * Iterator<Long> it = set.iterator(); // Must be in synchronized block 1676 * while (it.hasNext()) { 1677 * foo(it.next()); 1678 * } 1679 * } 1680 * }</pre> 1681 * 1682 * <p>Failure to follow this advice may result in non-deterministic behavior. 1683 * 1684 * <p>The returned bimap will be serializable if the specified bimap is serializable. 1685 * 1686 * @param bimap the bimap to be wrapped in a synchronized view 1687 * @return a synchronized view of the specified bimap 1688 */ 1689 @J2ktIncompatible // Synchronized 1690 public static <K extends @Nullable Object, V extends @Nullable Object> 1691 BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) { 1692 return Synchronized.biMap(bimap, null); 1693 } 1694 1695 /** 1696 * Returns an unmodifiable view of the specified bimap. This method allows modules to provide 1697 * users with "read-only" access to internal bimaps. Query operations on the returned bimap "read 1698 * through" to the specified bimap, and attempts to modify the returned map, whether direct or via 1699 * its collection views, result in an {@code UnsupportedOperationException}. 1700 * 1701 * <p>The returned bimap will be serializable if the specified bimap is serializable. 1702 * 1703 * @param bimap the bimap for which an unmodifiable view is to be returned 1704 * @return an unmodifiable view of the specified bimap 1705 */ 1706 public static <K extends @Nullable Object, V extends @Nullable Object> 1707 BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) { 1708 return new UnmodifiableBiMap<>(bimap, null); 1709 } 1710 1711 /** 1712 * @see Maps#unmodifiableBiMap(BiMap) 1713 */ 1714 private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object> 1715 extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { 1716 final Map<K, V> unmodifiableMap; 1717 final BiMap<? extends K, ? extends V> delegate; 1718 @LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse; 1719 @LazyInit @CheckForNull transient Set<V> values; 1720 1721 UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) { 1722 unmodifiableMap = Collections.unmodifiableMap(delegate); 1723 this.delegate = delegate; 1724 this.inverse = inverse; 1725 } 1726 1727 @Override 1728 protected Map<K, V> delegate() { 1729 return unmodifiableMap; 1730 } 1731 1732 @Override 1733 @CheckForNull 1734 public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { 1735 throw new UnsupportedOperationException(); 1736 } 1737 1738 @Override 1739 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 1740 throw new UnsupportedOperationException(); 1741 } 1742 1743 @Override 1744 @CheckForNull 1745 public V putIfAbsent(K key, V value) { 1746 throw new UnsupportedOperationException(); 1747 } 1748 1749 @Override 1750 public boolean remove(@Nullable Object key, @Nullable Object value) { 1751 throw new UnsupportedOperationException(); 1752 } 1753 1754 @Override 1755 public boolean replace(K key, V oldValue, V newValue) { 1756 throw new UnsupportedOperationException(); 1757 } 1758 1759 @Override 1760 @CheckForNull 1761 public V replace(K key, V value) { 1762 throw new UnsupportedOperationException(); 1763 } 1764 1765 @Override 1766 public V computeIfAbsent( 1767 K key, java.util.function.Function<? super K, ? extends V> mappingFunction) { 1768 throw new UnsupportedOperationException(); 1769 } 1770 1771 @Override 1772 @CheckForNull 1773 /* 1774 * Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs. 1775 * But it doesn't, which may be a sign that we still permit parameter contravariance in some 1776 * cases? 1777 */ 1778 public V computeIfPresent( 1779 K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { 1780 throw new UnsupportedOperationException(); 1781 } 1782 1783 @Override 1784 @CheckForNull 1785 public V compute( 1786 K key, 1787 BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { 1788 throw new UnsupportedOperationException(); 1789 } 1790 1791 @Override 1792 @CheckForNull 1793 public V merge( 1794 K key, 1795 @NonNull V value, 1796 BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) { 1797 throw new UnsupportedOperationException(); 1798 } 1799 1800 @Override 1801 public BiMap<V, K> inverse() { 1802 BiMap<V, K> result = inverse; 1803 return (result == null) 1804 ? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this) 1805 : result; 1806 } 1807 1808 @Override 1809 public Set<V> values() { 1810 Set<V> result = values; 1811 return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; 1812 } 1813 1814 private static final long serialVersionUID = 0; 1815 } 1816 1817 /** 1818 * Returns a view of a map where each value is transformed by a function. All other properties of 1819 * the map, such as iteration order, are left intact. For example, the code: 1820 * 1821 * <pre>{@code 1822 * Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); 1823 * Function<Integer, Double> sqrt = 1824 * new Function<Integer, Double>() { 1825 * public Double apply(Integer in) { 1826 * return Math.sqrt((int) in); 1827 * } 1828 * }; 1829 * Map<String, Double> transformed = Maps.transformValues(map, sqrt); 1830 * System.out.println(transformed); 1831 * }</pre> 1832 * 1833 * ... prints {@code {a=2.0, b=3.0}}. 1834 * 1835 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 1836 * removal operations, and these are reflected in the underlying map. 1837 * 1838 * <p>It's acceptable for the underlying map to contain null keys, and even null values provided 1839 * that the function is capable of accepting null input. The transformed map might contain null 1840 * values, if the function sometimes gives a null result. 1841 * 1842 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 1843 * 1844 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map 1845 * to be a view, but it means that the function will be applied many times for bulk operations 1846 * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code 1847 * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a 1848 * view, copy the returned map into a new map of your choosing. 1849 */ 1850 public static < 1851 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 1852 Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) { 1853 return transformEntries(fromMap, asEntryTransformer(function)); 1854 } 1855 1856 /** 1857 * Returns a view of a sorted map where each value is transformed by a function. All other 1858 * properties of the map, such as iteration order, are left intact. For example, the code: 1859 * 1860 * <pre>{@code 1861 * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); 1862 * Function<Integer, Double> sqrt = 1863 * new Function<Integer, Double>() { 1864 * public Double apply(Integer in) { 1865 * return Math.sqrt((int) in); 1866 * } 1867 * }; 1868 * SortedMap<String, Double> transformed = 1869 * Maps.transformValues(map, sqrt); 1870 * System.out.println(transformed); 1871 * }</pre> 1872 * 1873 * ... prints {@code {a=2.0, b=3.0}}. 1874 * 1875 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 1876 * removal operations, and these are reflected in the underlying map. 1877 * 1878 * <p>It's acceptable for the underlying map to contain null keys, and even null values provided 1879 * that the function is capable of accepting null input. The transformed map might contain null 1880 * values, if the function sometimes gives a null result. 1881 * 1882 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 1883 * 1884 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map 1885 * to be a view, but it means that the function will be applied many times for bulk operations 1886 * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code 1887 * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a 1888 * view, copy the returned map into a new map of your choosing. 1889 * 1890 * @since 11.0 1891 */ 1892 public static < 1893 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 1894 SortedMap<K, V2> transformValues( 1895 SortedMap<K, V1> fromMap, Function<? super V1, V2> function) { 1896 return transformEntries(fromMap, asEntryTransformer(function)); 1897 } 1898 1899 /** 1900 * Returns a view of a navigable map where each value is transformed by a function. All other 1901 * properties of the map, such as iteration order, are left intact. For example, the code: 1902 * 1903 * <pre>{@code 1904 * NavigableMap<String, Integer> map = Maps.newTreeMap(); 1905 * map.put("a", 4); 1906 * map.put("b", 9); 1907 * Function<Integer, Double> sqrt = 1908 * new Function<Integer, Double>() { 1909 * public Double apply(Integer in) { 1910 * return Math.sqrt((int) in); 1911 * } 1912 * }; 1913 * NavigableMap<String, Double> transformed = 1914 * Maps.transformNavigableValues(map, sqrt); 1915 * System.out.println(transformed); 1916 * }</pre> 1917 * 1918 * ... prints {@code {a=2.0, b=3.0}}. 1919 * 1920 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 1921 * removal operations, and these are reflected in the underlying map. 1922 * 1923 * <p>It's acceptable for the underlying map to contain null keys, and even null values provided 1924 * that the function is capable of accepting null input. The transformed map might contain null 1925 * values, if the function sometimes gives a null result. 1926 * 1927 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 1928 * 1929 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map 1930 * to be a view, but it means that the function will be applied many times for bulk operations 1931 * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code 1932 * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a 1933 * view, copy the returned map into a new map of your choosing. 1934 * 1935 * @since 13.0 1936 */ 1937 @GwtIncompatible // NavigableMap 1938 public static < 1939 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 1940 NavigableMap<K, V2> transformValues( 1941 NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) { 1942 return transformEntries(fromMap, asEntryTransformer(function)); 1943 } 1944 1945 /** 1946 * Returns a view of a map whose values are derived from the original map's entries. In contrast 1947 * to {@link #transformValues}, this method's entry-transformation logic may depend on the key as 1948 * well as the value. 1949 * 1950 * <p>All other properties of the transformed map, such as iteration order, are left intact. For 1951 * example, the code: 1952 * 1953 * <pre>{@code 1954 * Map<String, Boolean> options = 1955 * ImmutableMap.of("verbose", true, "sort", false); 1956 * EntryTransformer<String, Boolean, String> flagPrefixer = 1957 * new EntryTransformer<String, Boolean, String>() { 1958 * public String transformEntry(String key, Boolean value) { 1959 * return value ? key : "no" + key; 1960 * } 1961 * }; 1962 * Map<String, String> transformed = 1963 * Maps.transformEntries(options, flagPrefixer); 1964 * System.out.println(transformed); 1965 * }</pre> 1966 * 1967 * ... prints {@code {verbose=verbose, sort=nosort}}. 1968 * 1969 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 1970 * removal operations, and these are reflected in the underlying map. 1971 * 1972 * <p>It's acceptable for the underlying map to contain null keys and null values provided that 1973 * the transformer is capable of accepting null inputs. The transformed map might contain null 1974 * values if the transformer sometimes gives a null result. 1975 * 1976 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 1977 * 1978 * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned 1979 * map to be a view, but it means that the transformer will be applied many times for bulk 1980 * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform 1981 * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map 1982 * doesn't need to be a view, copy the returned map into a new map of your choosing. 1983 * 1984 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code 1985 * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of 1986 * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as 1987 * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the 1988 * transformed map. 1989 * 1990 * @since 7.0 1991 */ 1992 public static < 1993 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 1994 Map<K, V2> transformEntries( 1995 Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 1996 return new TransformedEntriesMap<>(fromMap, transformer); 1997 } 1998 1999 /** 2000 * Returns a view of a sorted map whose values are derived from the original sorted map's entries. 2001 * In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on 2002 * the key as well as the value. 2003 * 2004 * <p>All other properties of the transformed map, such as iteration order, are left intact. For 2005 * example, the code: 2006 * 2007 * <pre>{@code 2008 * Map<String, Boolean> options = 2009 * ImmutableSortedMap.of("verbose", true, "sort", false); 2010 * EntryTransformer<String, Boolean, String> flagPrefixer = 2011 * new EntryTransformer<String, Boolean, String>() { 2012 * public String transformEntry(String key, Boolean value) { 2013 * return value ? key : "yes" + key; 2014 * } 2015 * }; 2016 * SortedMap<String, String> transformed = 2017 * Maps.transformEntries(options, flagPrefixer); 2018 * System.out.println(transformed); 2019 * }</pre> 2020 * 2021 * ... prints {@code {sort=yessort, verbose=verbose}}. 2022 * 2023 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 2024 * removal operations, and these are reflected in the underlying map. 2025 * 2026 * <p>It's acceptable for the underlying map to contain null keys and null values provided that 2027 * the transformer is capable of accepting null inputs. The transformed map might contain null 2028 * values if the transformer sometimes gives a null result. 2029 * 2030 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 2031 * 2032 * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned 2033 * map to be a view, but it means that the transformer will be applied many times for bulk 2034 * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform 2035 * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map 2036 * doesn't need to be a view, copy the returned map into a new map of your choosing. 2037 * 2038 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code 2039 * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of 2040 * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as 2041 * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the 2042 * transformed map. 2043 * 2044 * @since 11.0 2045 */ 2046 public static < 2047 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2048 SortedMap<K, V2> transformEntries( 2049 SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 2050 return new TransformedEntriesSortedMap<>(fromMap, transformer); 2051 } 2052 2053 /** 2054 * Returns a view of a navigable map whose values are derived from the original navigable map's 2055 * entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may 2056 * depend on the key as well as the value. 2057 * 2058 * <p>All other properties of the transformed map, such as iteration order, are left intact. For 2059 * example, the code: 2060 * 2061 * <pre>{@code 2062 * NavigableMap<String, Boolean> options = Maps.newTreeMap(); 2063 * options.put("verbose", false); 2064 * options.put("sort", true); 2065 * EntryTransformer<String, Boolean, String> flagPrefixer = 2066 * new EntryTransformer<String, Boolean, String>() { 2067 * public String transformEntry(String key, Boolean value) { 2068 * return value ? key : ("yes" + key); 2069 * } 2070 * }; 2071 * NavigableMap<String, String> transformed = 2072 * LabsMaps.transformNavigableEntries(options, flagPrefixer); 2073 * System.out.println(transformed); 2074 * }</pre> 2075 * 2076 * ... prints {@code {sort=yessort, verbose=verbose}}. 2077 * 2078 * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports 2079 * removal operations, and these are reflected in the underlying map. 2080 * 2081 * <p>It's acceptable for the underlying map to contain null keys and null values provided that 2082 * the transformer is capable of accepting null inputs. The transformed map might contain null 2083 * values if the transformer sometimes gives a null result. 2084 * 2085 * <p>The returned map is not thread-safe or serializable, even if the underlying map is. 2086 * 2087 * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned 2088 * map to be a view, but it means that the transformer will be applied many times for bulk 2089 * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform 2090 * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map 2091 * doesn't need to be a view, copy the returned map into a new map of your choosing. 2092 * 2093 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code 2094 * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of 2095 * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as 2096 * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the 2097 * transformed map. 2098 * 2099 * @since 13.0 2100 */ 2101 @GwtIncompatible // NavigableMap 2102 public static < 2103 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2104 NavigableMap<K, V2> transformEntries( 2105 NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 2106 return new TransformedEntriesNavigableMap<>(fromMap, transformer); 2107 } 2108 2109 /** 2110 * A transformation of the value of a key-value pair, using both key and value as inputs. To apply 2111 * the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}. 2112 * 2113 * @param <K> the key type of the input and output entries 2114 * @param <V1> the value type of the input entry 2115 * @param <V2> the value type of the output entry 2116 * @since 7.0 2117 */ 2118 @FunctionalInterface 2119 public interface EntryTransformer< 2120 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> { 2121 /** 2122 * Determines an output value based on a key-value pair. This method is <i>generally 2123 * expected</i>, but not absolutely required, to have the following properties: 2124 * 2125 * <ul> 2126 * <li>Its execution does not cause any observable side effects. 2127 * <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal 2128 * Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that 2129 * {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}. 2130 * </ul> 2131 * 2132 * @throws NullPointerException if the key or value is null and this transformer does not accept 2133 * null arguments 2134 */ 2135 @ParametricNullness 2136 V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value); 2137 } 2138 2139 /** Views a function as an entry transformer that ignores the entry key. */ 2140 static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2141 EntryTransformer<K, V1, V2> asEntryTransformer(final Function<? super V1, V2> function) { 2142 checkNotNull(function); 2143 return new EntryTransformer<K, V1, V2>() { 2144 @Override 2145 @ParametricNullness 2146 public V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value) { 2147 return function.apply(value); 2148 } 2149 }; 2150 } 2151 2152 static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2153 Function<V1, V2> asValueToValueFunction( 2154 final EntryTransformer<? super K, V1, V2> transformer, @ParametricNullness final K key) { 2155 checkNotNull(transformer); 2156 return new Function<V1, V2>() { 2157 @Override 2158 @ParametricNullness 2159 public V2 apply(@ParametricNullness V1 v1) { 2160 return transformer.transformEntry(key, v1); 2161 } 2162 }; 2163 } 2164 2165 /** Views an entry transformer as a function from {@code Entry} to values. */ 2166 static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2167 Function<Entry<K, V1>, V2> asEntryToValueFunction( 2168 final EntryTransformer<? super K, ? super V1, V2> transformer) { 2169 checkNotNull(transformer); 2170 return new Function<Entry<K, V1>, V2>() { 2171 @Override 2172 @ParametricNullness 2173 public V2 apply(Entry<K, V1> entry) { 2174 return transformer.transformEntry(entry.getKey(), entry.getValue()); 2175 } 2176 }; 2177 } 2178 2179 /** Returns a view of an entry transformed by the specified transformer. */ 2180 static <V2 extends @Nullable Object, K extends @Nullable Object, V1 extends @Nullable Object> 2181 Entry<K, V2> transformEntry( 2182 final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) { 2183 checkNotNull(transformer); 2184 checkNotNull(entry); 2185 return new AbstractMapEntry<K, V2>() { 2186 @Override 2187 @ParametricNullness 2188 public K getKey() { 2189 return entry.getKey(); 2190 } 2191 2192 @Override 2193 @ParametricNullness 2194 public V2 getValue() { 2195 return transformer.transformEntry(entry.getKey(), entry.getValue()); 2196 } 2197 }; 2198 } 2199 2200 /** Views an entry transformer as a function from entries to entries. */ 2201 static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2202 Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction( 2203 final EntryTransformer<? super K, ? super V1, V2> transformer) { 2204 checkNotNull(transformer); 2205 return new Function<Entry<K, V1>, Entry<K, V2>>() { 2206 @Override 2207 public Entry<K, V2> apply(final Entry<K, V1> entry) { 2208 return transformEntry(transformer, entry); 2209 } 2210 }; 2211 } 2212 2213 static class TransformedEntriesMap< 2214 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2215 extends IteratorBasedAbstractMap<K, V2> { 2216 final Map<K, V1> fromMap; 2217 final EntryTransformer<? super K, ? super V1, V2> transformer; 2218 2219 TransformedEntriesMap( 2220 Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 2221 this.fromMap = checkNotNull(fromMap); 2222 this.transformer = checkNotNull(transformer); 2223 } 2224 2225 @Override 2226 public int size() { 2227 return fromMap.size(); 2228 } 2229 2230 @Override 2231 public boolean containsKey(@CheckForNull Object key) { 2232 return fromMap.containsKey(key); 2233 } 2234 2235 @Override 2236 @CheckForNull 2237 public V2 get(@CheckForNull Object key) { 2238 return getOrDefault(key, null); 2239 } 2240 2241 // safe as long as the user followed the <b>Warning</b> in the javadoc 2242 @SuppressWarnings("unchecked") 2243 @Override 2244 @CheckForNull 2245 public V2 getOrDefault(@CheckForNull Object key, @CheckForNull V2 defaultValue) { 2246 V1 value = fromMap.get(key); 2247 if (value != null || fromMap.containsKey(key)) { 2248 // The cast is safe because of the containsKey check. 2249 return transformer.transformEntry((K) key, uncheckedCastNullableTToT(value)); 2250 } 2251 return defaultValue; 2252 } 2253 2254 // safe as long as the user followed the <b>Warning</b> in the javadoc 2255 @SuppressWarnings("unchecked") 2256 @Override 2257 @CheckForNull 2258 public V2 remove(@CheckForNull Object key) { 2259 return fromMap.containsKey(key) 2260 // The cast is safe because of the containsKey check. 2261 ? transformer.transformEntry((K) key, uncheckedCastNullableTToT(fromMap.remove(key))) 2262 : null; 2263 } 2264 2265 @Override 2266 public void clear() { 2267 fromMap.clear(); 2268 } 2269 2270 @Override 2271 public Set<K> keySet() { 2272 return fromMap.keySet(); 2273 } 2274 2275 @Override 2276 Iterator<Entry<K, V2>> entryIterator() { 2277 return Iterators.transform( 2278 fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); 2279 } 2280 2281 @Override 2282 Spliterator<Entry<K, V2>> entrySpliterator() { 2283 return CollectSpliterators.map( 2284 fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); 2285 } 2286 2287 @Override 2288 public void forEach(BiConsumer<? super K, ? super V2> action) { 2289 checkNotNull(action); 2290 // avoids creating new Entry<K, V2> objects 2291 fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1))); 2292 } 2293 2294 @Override 2295 public Collection<V2> values() { 2296 return new Values<>(this); 2297 } 2298 } 2299 2300 static class TransformedEntriesSortedMap< 2301 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2302 extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> { 2303 2304 protected SortedMap<K, V1> fromMap() { 2305 return (SortedMap<K, V1>) fromMap; 2306 } 2307 2308 TransformedEntriesSortedMap( 2309 SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 2310 super(fromMap, transformer); 2311 } 2312 2313 @Override 2314 @CheckForNull 2315 public Comparator<? super K> comparator() { 2316 return fromMap().comparator(); 2317 } 2318 2319 @Override 2320 @ParametricNullness 2321 public K firstKey() { 2322 return fromMap().firstKey(); 2323 } 2324 2325 @Override 2326 public SortedMap<K, V2> headMap(@ParametricNullness K toKey) { 2327 return transformEntries(fromMap().headMap(toKey), transformer); 2328 } 2329 2330 @Override 2331 @ParametricNullness 2332 public K lastKey() { 2333 return fromMap().lastKey(); 2334 } 2335 2336 @Override 2337 public SortedMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 2338 return transformEntries(fromMap().subMap(fromKey, toKey), transformer); 2339 } 2340 2341 @Override 2342 public SortedMap<K, V2> tailMap(@ParametricNullness K fromKey) { 2343 return transformEntries(fromMap().tailMap(fromKey), transformer); 2344 } 2345 } 2346 2347 @GwtIncompatible // NavigableMap 2348 private static class TransformedEntriesNavigableMap< 2349 K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> 2350 extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> { 2351 2352 TransformedEntriesNavigableMap( 2353 NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 2354 super(fromMap, transformer); 2355 } 2356 2357 @Override 2358 @CheckForNull 2359 public Entry<K, V2> ceilingEntry(@ParametricNullness K key) { 2360 return transformEntry(fromMap().ceilingEntry(key)); 2361 } 2362 2363 @Override 2364 @CheckForNull 2365 public K ceilingKey(@ParametricNullness K key) { 2366 return fromMap().ceilingKey(key); 2367 } 2368 2369 @Override 2370 public NavigableSet<K> descendingKeySet() { 2371 return fromMap().descendingKeySet(); 2372 } 2373 2374 @Override 2375 public NavigableMap<K, V2> descendingMap() { 2376 return transformEntries(fromMap().descendingMap(), transformer); 2377 } 2378 2379 @Override 2380 @CheckForNull 2381 public Entry<K, V2> firstEntry() { 2382 return transformEntry(fromMap().firstEntry()); 2383 } 2384 2385 @Override 2386 @CheckForNull 2387 public Entry<K, V2> floorEntry(@ParametricNullness K key) { 2388 return transformEntry(fromMap().floorEntry(key)); 2389 } 2390 2391 @Override 2392 @CheckForNull 2393 public K floorKey(@ParametricNullness K key) { 2394 return fromMap().floorKey(key); 2395 } 2396 2397 @Override 2398 public NavigableMap<K, V2> headMap(@ParametricNullness K toKey) { 2399 return headMap(toKey, false); 2400 } 2401 2402 @Override 2403 public NavigableMap<K, V2> headMap(@ParametricNullness K toKey, boolean inclusive) { 2404 return transformEntries(fromMap().headMap(toKey, inclusive), transformer); 2405 } 2406 2407 @Override 2408 @CheckForNull 2409 public Entry<K, V2> higherEntry(@ParametricNullness K key) { 2410 return transformEntry(fromMap().higherEntry(key)); 2411 } 2412 2413 @Override 2414 @CheckForNull 2415 public K higherKey(@ParametricNullness K key) { 2416 return fromMap().higherKey(key); 2417 } 2418 2419 @Override 2420 @CheckForNull 2421 public Entry<K, V2> lastEntry() { 2422 return transformEntry(fromMap().lastEntry()); 2423 } 2424 2425 @Override 2426 @CheckForNull 2427 public Entry<K, V2> lowerEntry(@ParametricNullness K key) { 2428 return transformEntry(fromMap().lowerEntry(key)); 2429 } 2430 2431 @Override 2432 @CheckForNull 2433 public K lowerKey(@ParametricNullness K key) { 2434 return fromMap().lowerKey(key); 2435 } 2436 2437 @Override 2438 public NavigableSet<K> navigableKeySet() { 2439 return fromMap().navigableKeySet(); 2440 } 2441 2442 @Override 2443 @CheckForNull 2444 public Entry<K, V2> pollFirstEntry() { 2445 return transformEntry(fromMap().pollFirstEntry()); 2446 } 2447 2448 @Override 2449 @CheckForNull 2450 public Entry<K, V2> pollLastEntry() { 2451 return transformEntry(fromMap().pollLastEntry()); 2452 } 2453 2454 @Override 2455 public NavigableMap<K, V2> subMap( 2456 @ParametricNullness K fromKey, 2457 boolean fromInclusive, 2458 @ParametricNullness K toKey, 2459 boolean toInclusive) { 2460 return transformEntries( 2461 fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); 2462 } 2463 2464 @Override 2465 public NavigableMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 2466 return subMap(fromKey, true, toKey, false); 2467 } 2468 2469 @Override 2470 public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey) { 2471 return tailMap(fromKey, true); 2472 } 2473 2474 @Override 2475 public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey, boolean inclusive) { 2476 return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer); 2477 } 2478 2479 @CheckForNull 2480 private Entry<K, V2> transformEntry(@CheckForNull Entry<K, V1> entry) { 2481 return (entry == null) ? null : Maps.transformEntry(transformer, entry); 2482 } 2483 2484 @Override 2485 protected NavigableMap<K, V1> fromMap() { 2486 return (NavigableMap<K, V1>) super.fromMap(); 2487 } 2488 } 2489 2490 static <K extends @Nullable Object> Predicate<Entry<K, ?>> keyPredicateOnEntries( 2491 Predicate<? super K> keyPredicate) { 2492 return compose(keyPredicate, Maps.<K>keyFunction()); 2493 } 2494 2495 static <V extends @Nullable Object> Predicate<Entry<?, V>> valuePredicateOnEntries( 2496 Predicate<? super V> valuePredicate) { 2497 return compose(valuePredicate, Maps.<V>valueFunction()); 2498 } 2499 2500 /** 2501 * Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The 2502 * returned map is a live view of {@code unfiltered}; changes to one affect the other. 2503 * 2504 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2505 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2506 * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and 2507 * {@code putAll()} methods throw an {@link IllegalArgumentException}. 2508 * 2509 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2510 * or its views, only mappings whose keys satisfy the filter will be removed from the underlying 2511 * map. 2512 * 2513 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2514 * 2515 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2516 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2517 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2518 * 2519 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 2520 * {@link Predicate#apply}. Do not provide a predicate such as {@code 2521 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2522 */ 2523 public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterKeys( 2524 Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 2525 checkNotNull(keyPredicate); 2526 Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate); 2527 return (unfiltered instanceof AbstractFilteredMap) 2528 ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) 2529 : new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate); 2530 } 2531 2532 /** 2533 * Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a 2534 * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the 2535 * other. 2536 * 2537 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2538 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2539 * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and 2540 * {@code putAll()} methods throw an {@link IllegalArgumentException}. 2541 * 2542 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2543 * or its views, only mappings whose keys satisfy the filter will be removed from the underlying 2544 * map. 2545 * 2546 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2547 * 2548 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2549 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2550 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2551 * 2552 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 2553 * {@link Predicate#apply}. Do not provide a predicate such as {@code 2554 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2555 * 2556 * @since 11.0 2557 */ 2558 public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterKeys( 2559 SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 2560 // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better 2561 // performance. 2562 return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); 2563 } 2564 2565 /** 2566 * Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a 2567 * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the 2568 * other. 2569 * 2570 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2571 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2572 * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and 2573 * {@code putAll()} methods throw an {@link IllegalArgumentException}. 2574 * 2575 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2576 * or its views, only mappings whose keys satisfy the filter will be removed from the underlying 2577 * map. 2578 * 2579 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2580 * 2581 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2582 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2583 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2584 * 2585 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 2586 * {@link Predicate#apply}. Do not provide a predicate such as {@code 2587 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2588 * 2589 * @since 14.0 2590 */ 2591 @GwtIncompatible // NavigableMap 2592 public static <K extends @Nullable Object, V extends @Nullable Object> 2593 NavigableMap<K, V> filterKeys( 2594 NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 2595 // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better 2596 // performance. 2597 return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); 2598 } 2599 2600 /** 2601 * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate. 2602 * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. 2603 * 2604 * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2605 * iterators that don't support {@code remove()}, but all other methods are supported by the bimap 2606 * and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()}, 2607 * {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. 2608 * 2609 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2610 * bimap or its views, only mappings that satisfy the filter will be removed from the underlying 2611 * bimap. 2612 * 2613 * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2614 * 2615 * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in 2616 * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> 2617 * needed, it may be faster to copy the filtered bimap and use the copy. 2618 * 2619 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented 2620 * at {@link Predicate#apply}. 2621 * 2622 * @since 14.0 2623 */ 2624 public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterKeys( 2625 BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 2626 checkNotNull(keyPredicate); 2627 return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); 2628 } 2629 2630 /** 2631 * Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate. 2632 * The returned map is a live view of {@code unfiltered}; changes to one affect the other. 2633 * 2634 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2635 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2636 * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, 2637 * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. 2638 * 2639 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2640 * or its views, only mappings whose values satisfy the filter will be removed from the underlying 2641 * map. 2642 * 2643 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2644 * 2645 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2646 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2647 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2648 * 2649 * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented 2650 * at {@link Predicate#apply}. Do not provide a predicate such as {@code 2651 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2652 */ 2653 public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterValues( 2654 Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2655 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2656 } 2657 2658 /** 2659 * Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a 2660 * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the 2661 * other. 2662 * 2663 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2664 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2665 * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, 2666 * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. 2667 * 2668 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2669 * or its views, only mappings whose values satisfy the filter will be removed from the underlying 2670 * map. 2671 * 2672 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2673 * 2674 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2675 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2676 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2677 * 2678 * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented 2679 * at {@link Predicate#apply}. Do not provide a predicate such as {@code 2680 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2681 * 2682 * @since 11.0 2683 */ 2684 public static <K extends @Nullable Object, V extends @Nullable Object> 2685 SortedMap<K, V> filterValues( 2686 SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2687 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2688 } 2689 2690 /** 2691 * Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a 2692 * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the 2693 * other. 2694 * 2695 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2696 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2697 * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, 2698 * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. 2699 * 2700 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2701 * or its views, only mappings whose values satisfy the filter will be removed from the underlying 2702 * map. 2703 * 2704 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2705 * 2706 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2707 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2708 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2709 * 2710 * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented 2711 * at {@link Predicate#apply}. Do not provide a predicate such as {@code 2712 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2713 * 2714 * @since 14.0 2715 */ 2716 @GwtIncompatible // NavigableMap 2717 public static <K extends @Nullable Object, V extends @Nullable Object> 2718 NavigableMap<K, V> filterValues( 2719 NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2720 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2721 } 2722 2723 /** 2724 * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate. 2725 * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. 2726 * 2727 * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2728 * iterators that don't support {@code remove()}, but all other methods are supported by the bimap 2729 * and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code 2730 * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link 2731 * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method 2732 * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the 2733 * predicate. 2734 * 2735 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2736 * bimap or its views, only mappings that satisfy the filter will be removed from the underlying 2737 * bimap. 2738 * 2739 * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2740 * 2741 * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in 2742 * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> 2743 * needed, it may be faster to copy the filtered bimap and use the copy. 2744 * 2745 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented 2746 * at {@link Predicate#apply}. 2747 * 2748 * @since 14.0 2749 */ 2750 public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterValues( 2751 BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2752 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2753 } 2754 2755 /** 2756 * Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The 2757 * returned map is a live view of {@code unfiltered}; changes to one affect the other. 2758 * 2759 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2760 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2761 * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code 2762 * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the 2763 * map's entries have a {@link Entry#setValue} method that throws an {@link 2764 * IllegalArgumentException} when the existing key and the provided value don't satisfy the 2765 * predicate. 2766 * 2767 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2768 * or its views, only mappings that satisfy the filter will be removed from the underlying map. 2769 * 2770 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2771 * 2772 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2773 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2774 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2775 * 2776 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented 2777 * at {@link Predicate#apply}. 2778 */ 2779 public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterEntries( 2780 Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2781 checkNotNull(entryPredicate); 2782 return (unfiltered instanceof AbstractFilteredMap) 2783 ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) 2784 : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate); 2785 } 2786 2787 /** 2788 * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate. 2789 * The returned map is a live view of {@code unfiltered}; changes to one affect the other. 2790 * 2791 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2792 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2793 * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code 2794 * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the 2795 * map's entries have a {@link Entry#setValue} method that throws an {@link 2796 * IllegalArgumentException} when the existing key and the provided value don't satisfy the 2797 * predicate. 2798 * 2799 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2800 * or its views, only mappings that satisfy the filter will be removed from the underlying map. 2801 * 2802 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2803 * 2804 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2805 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2806 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2807 * 2808 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented 2809 * at {@link Predicate#apply}. 2810 * 2811 * @since 11.0 2812 */ 2813 public static <K extends @Nullable Object, V extends @Nullable Object> 2814 SortedMap<K, V> filterEntries( 2815 SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2816 checkNotNull(entryPredicate); 2817 return (unfiltered instanceof FilteredEntrySortedMap) 2818 ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate) 2819 : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate); 2820 } 2821 2822 /** 2823 * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate. 2824 * The returned map is a live view of {@code unfiltered}; changes to one affect the other. 2825 * 2826 * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2827 * iterators that don't support {@code remove()}, but all other methods are supported by the map 2828 * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code 2829 * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the 2830 * map's entries have a {@link Entry#setValue} method that throws an {@link 2831 * IllegalArgumentException} when the existing key and the provided value don't satisfy the 2832 * predicate. 2833 * 2834 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map 2835 * or its views, only mappings that satisfy the filter will be removed from the underlying map. 2836 * 2837 * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. 2838 * 2839 * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value 2840 * mapping in the underlying map and determine which satisfy the filter. When a live view is 2841 * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. 2842 * 2843 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented 2844 * at {@link Predicate#apply}. 2845 * 2846 * @since 14.0 2847 */ 2848 @GwtIncompatible // NavigableMap 2849 public static <K extends @Nullable Object, V extends @Nullable Object> 2850 NavigableMap<K, V> filterEntries( 2851 NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2852 checkNotNull(entryPredicate); 2853 return (unfiltered instanceof FilteredEntryNavigableMap) 2854 ? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate) 2855 : new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate); 2856 } 2857 2858 /** 2859 * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The 2860 * returned bimap is a live view of {@code unfiltered}; changes to one affect the other. 2861 * 2862 * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have 2863 * iterators that don't support {@code remove()}, but all other methods are supported by the bimap 2864 * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's 2865 * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link 2866 * IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method 2867 * that throws an {@link IllegalArgumentException} when the existing key and the provided value 2868 * don't satisfy the predicate. 2869 * 2870 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2871 * bimap or its views, only mappings that satisfy the filter will be removed from the underlying 2872 * bimap. 2873 * 2874 * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2875 * 2876 * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value 2877 * mapping in the underlying bimap and determine which satisfy the filter. When a live view is 2878 * <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy. 2879 * 2880 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented 2881 * at {@link Predicate#apply}. 2882 * 2883 * @since 14.0 2884 */ 2885 public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterEntries( 2886 BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2887 checkNotNull(unfiltered); 2888 checkNotNull(entryPredicate); 2889 return (unfiltered instanceof FilteredEntryBiMap) 2890 ? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate) 2891 : new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate); 2892 } 2893 2894 /** 2895 * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered 2896 * map. 2897 */ 2898 private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterFiltered( 2899 AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { 2900 return new FilteredEntryMap<>( 2901 map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate)); 2902 } 2903 2904 /** 2905 * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered 2906 * sorted map. 2907 */ 2908 private static <K extends @Nullable Object, V extends @Nullable Object> 2909 SortedMap<K, V> filterFiltered( 2910 FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { 2911 Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate); 2912 return new FilteredEntrySortedMap<>(map.sortedMap(), predicate); 2913 } 2914 2915 /** 2916 * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered 2917 * navigable map. 2918 */ 2919 @GwtIncompatible // NavigableMap 2920 private static <K extends @Nullable Object, V extends @Nullable Object> 2921 NavigableMap<K, V> filterFiltered( 2922 FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { 2923 Predicate<Entry<K, V>> predicate = 2924 Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate); 2925 return new FilteredEntryNavigableMap<>(map.unfiltered, predicate); 2926 } 2927 2928 /** 2929 * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered 2930 * map. 2931 */ 2932 private static <K extends @Nullable Object, V extends @Nullable Object> 2933 BiMap<K, V> filterFiltered( 2934 FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { 2935 Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate); 2936 return new FilteredEntryBiMap<>(map.unfiltered(), predicate); 2937 } 2938 2939 private abstract static class AbstractFilteredMap< 2940 K extends @Nullable Object, V extends @Nullable Object> 2941 extends ViewCachingAbstractMap<K, V> { 2942 final Map<K, V> unfiltered; 2943 final Predicate<? super Entry<K, V>> predicate; 2944 2945 AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { 2946 this.unfiltered = unfiltered; 2947 this.predicate = predicate; 2948 } 2949 2950 boolean apply(@CheckForNull Object key, @ParametricNullness V value) { 2951 // This method is called only when the key is in the map (or about to be added to the map), 2952 // implying that key is a K. 2953 @SuppressWarnings({"unchecked", "nullness"}) 2954 K k = (K) key; 2955 return predicate.apply(Maps.immutableEntry(k, value)); 2956 } 2957 2958 @Override 2959 @CheckForNull 2960 public V put(@ParametricNullness K key, @ParametricNullness V value) { 2961 checkArgument(apply(key, value)); 2962 return unfiltered.put(key, value); 2963 } 2964 2965 @Override 2966 public void putAll(Map<? extends K, ? extends V> map) { 2967 for (Entry<? extends K, ? extends V> entry : map.entrySet()) { 2968 checkArgument(apply(entry.getKey(), entry.getValue())); 2969 } 2970 unfiltered.putAll(map); 2971 } 2972 2973 @Override 2974 public boolean containsKey(@CheckForNull Object key) { 2975 return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); 2976 } 2977 2978 @Override 2979 @CheckForNull 2980 public V get(@CheckForNull Object key) { 2981 V value = unfiltered.get(key); 2982 return ((value != null) && apply(key, value)) ? value : null; 2983 } 2984 2985 @Override 2986 public boolean isEmpty() { 2987 return entrySet().isEmpty(); 2988 } 2989 2990 @Override 2991 @CheckForNull 2992 public V remove(@CheckForNull Object key) { 2993 return containsKey(key) ? unfiltered.remove(key) : null; 2994 } 2995 2996 @Override 2997 Collection<V> createValues() { 2998 return new FilteredMapValues<>(this, unfiltered, predicate); 2999 } 3000 } 3001 3002 private static final class FilteredMapValues< 3003 K extends @Nullable Object, V extends @Nullable Object> 3004 extends Maps.Values<K, V> { 3005 final Map<K, V> unfiltered; 3006 final Predicate<? super Entry<K, V>> predicate; 3007 3008 FilteredMapValues( 3009 Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { 3010 super(filteredMap); 3011 this.unfiltered = unfiltered; 3012 this.predicate = predicate; 3013 } 3014 3015 @Override 3016 public boolean remove(@CheckForNull Object o) { 3017 Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); 3018 while (entryItr.hasNext()) { 3019 Entry<K, V> entry = entryItr.next(); 3020 if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) { 3021 entryItr.remove(); 3022 return true; 3023 } 3024 } 3025 return false; 3026 } 3027 3028 @Override 3029 public boolean removeAll(Collection<?> collection) { 3030 Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); 3031 boolean result = false; 3032 while (entryItr.hasNext()) { 3033 Entry<K, V> entry = entryItr.next(); 3034 if (predicate.apply(entry) && collection.contains(entry.getValue())) { 3035 entryItr.remove(); 3036 result = true; 3037 } 3038 } 3039 return result; 3040 } 3041 3042 @Override 3043 public boolean retainAll(Collection<?> collection) { 3044 Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); 3045 boolean result = false; 3046 while (entryItr.hasNext()) { 3047 Entry<K, V> entry = entryItr.next(); 3048 if (predicate.apply(entry) && !collection.contains(entry.getValue())) { 3049 entryItr.remove(); 3050 result = true; 3051 } 3052 } 3053 return result; 3054 } 3055 3056 @Override 3057 public @Nullable Object[] toArray() { 3058 // creating an ArrayList so filtering happens once 3059 return Lists.newArrayList(iterator()).toArray(); 3060 } 3061 3062 @Override 3063 @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations 3064 public <T extends @Nullable Object> T[] toArray(T[] array) { 3065 return Lists.newArrayList(iterator()).toArray(array); 3066 } 3067 } 3068 3069 private static class FilteredKeyMap<K extends @Nullable Object, V extends @Nullable Object> 3070 extends AbstractFilteredMap<K, V> { 3071 final Predicate<? super K> keyPredicate; 3072 3073 FilteredKeyMap( 3074 Map<K, V> unfiltered, 3075 Predicate<? super K> keyPredicate, 3076 Predicate<? super Entry<K, V>> entryPredicate) { 3077 super(unfiltered, entryPredicate); 3078 this.keyPredicate = keyPredicate; 3079 } 3080 3081 @Override 3082 protected Set<Entry<K, V>> createEntrySet() { 3083 return Sets.filter(unfiltered.entrySet(), predicate); 3084 } 3085 3086 @Override 3087 Set<K> createKeySet() { 3088 return Sets.filter(unfiltered.keySet(), keyPredicate); 3089 } 3090 3091 // The cast is called only when the key is in the unfiltered map, implying 3092 // that key is a K. 3093 @Override 3094 @SuppressWarnings("unchecked") 3095 public boolean containsKey(@CheckForNull Object key) { 3096 return unfiltered.containsKey(key) && keyPredicate.apply((K) key); 3097 } 3098 } 3099 3100 static class FilteredEntryMap<K extends @Nullable Object, V extends @Nullable Object> 3101 extends AbstractFilteredMap<K, V> { 3102 /** 3103 * Entries in this set satisfy the predicate, but they don't validate the input to {@code 3104 * Entry.setValue()}. 3105 */ 3106 final Set<Entry<K, V>> filteredEntrySet; 3107 3108 FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 3109 super(unfiltered, entryPredicate); 3110 filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); 3111 } 3112 3113 @Override 3114 protected Set<Entry<K, V>> createEntrySet() { 3115 return new EntrySet(); 3116 } 3117 3118 @WeakOuter 3119 private class EntrySet extends ForwardingSet<Entry<K, V>> { 3120 @Override 3121 protected Set<Entry<K, V>> delegate() { 3122 return filteredEntrySet; 3123 } 3124 3125 @Override 3126 public Iterator<Entry<K, V>> iterator() { 3127 return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) { 3128 @Override 3129 Entry<K, V> transform(final Entry<K, V> entry) { 3130 return new ForwardingMapEntry<K, V>() { 3131 @Override 3132 protected Entry<K, V> delegate() { 3133 return entry; 3134 } 3135 3136 @Override 3137 @ParametricNullness 3138 public V setValue(@ParametricNullness V newValue) { 3139 checkArgument(apply(getKey(), newValue)); 3140 return super.setValue(newValue); 3141 } 3142 }; 3143 } 3144 }; 3145 } 3146 } 3147 3148 @Override 3149 Set<K> createKeySet() { 3150 return new KeySet(); 3151 } 3152 3153 static <K extends @Nullable Object, V extends @Nullable Object> boolean removeAllKeys( 3154 Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) { 3155 Iterator<Entry<K, V>> entryItr = map.entrySet().iterator(); 3156 boolean result = false; 3157 while (entryItr.hasNext()) { 3158 Entry<K, V> entry = entryItr.next(); 3159 if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) { 3160 entryItr.remove(); 3161 result = true; 3162 } 3163 } 3164 return result; 3165 } 3166 3167 static <K extends @Nullable Object, V extends @Nullable Object> boolean retainAllKeys( 3168 Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) { 3169 Iterator<Entry<K, V>> entryItr = map.entrySet().iterator(); 3170 boolean result = false; 3171 while (entryItr.hasNext()) { 3172 Entry<K, V> entry = entryItr.next(); 3173 if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) { 3174 entryItr.remove(); 3175 result = true; 3176 } 3177 } 3178 return result; 3179 } 3180 3181 @WeakOuter 3182 class KeySet extends Maps.KeySet<K, V> { 3183 KeySet() { 3184 super(FilteredEntryMap.this); 3185 } 3186 3187 @Override 3188 public boolean remove(@CheckForNull Object o) { 3189 if (containsKey(o)) { 3190 unfiltered.remove(o); 3191 return true; 3192 } 3193 return false; 3194 } 3195 3196 @Override 3197 public boolean removeAll(Collection<?> collection) { 3198 return removeAllKeys(unfiltered, predicate, collection); 3199 } 3200 3201 @Override 3202 public boolean retainAll(Collection<?> collection) { 3203 return retainAllKeys(unfiltered, predicate, collection); 3204 } 3205 3206 @Override 3207 public @Nullable Object[] toArray() { 3208 // creating an ArrayList so filtering happens once 3209 return Lists.newArrayList(iterator()).toArray(); 3210 } 3211 3212 @Override 3213 @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations 3214 public <T extends @Nullable Object> T[] toArray(T[] array) { 3215 return Lists.newArrayList(iterator()).toArray(array); 3216 } 3217 } 3218 } 3219 3220 private static class FilteredEntrySortedMap< 3221 K extends @Nullable Object, V extends @Nullable Object> 3222 extends FilteredEntryMap<K, V> implements SortedMap<K, V> { 3223 3224 FilteredEntrySortedMap( 3225 SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 3226 super(unfiltered, entryPredicate); 3227 } 3228 3229 SortedMap<K, V> sortedMap() { 3230 return (SortedMap<K, V>) unfiltered; 3231 } 3232 3233 @Override 3234 public SortedSet<K> keySet() { 3235 return (SortedSet<K>) super.keySet(); 3236 } 3237 3238 @Override 3239 SortedSet<K> createKeySet() { 3240 return new SortedKeySet(); 3241 } 3242 3243 @WeakOuter 3244 class SortedKeySet extends KeySet implements SortedSet<K> { 3245 @Override 3246 @CheckForNull 3247 public Comparator<? super K> comparator() { 3248 return sortedMap().comparator(); 3249 } 3250 3251 @Override 3252 public SortedSet<K> subSet( 3253 @ParametricNullness K fromElement, @ParametricNullness K toElement) { 3254 return (SortedSet<K>) subMap(fromElement, toElement).keySet(); 3255 } 3256 3257 @Override 3258 public SortedSet<K> headSet(@ParametricNullness K toElement) { 3259 return (SortedSet<K>) headMap(toElement).keySet(); 3260 } 3261 3262 @Override 3263 public SortedSet<K> tailSet(@ParametricNullness K fromElement) { 3264 return (SortedSet<K>) tailMap(fromElement).keySet(); 3265 } 3266 3267 @Override 3268 @ParametricNullness 3269 public K first() { 3270 return firstKey(); 3271 } 3272 3273 @Override 3274 @ParametricNullness 3275 public K last() { 3276 return lastKey(); 3277 } 3278 } 3279 3280 @Override 3281 @CheckForNull 3282 public Comparator<? super K> comparator() { 3283 return sortedMap().comparator(); 3284 } 3285 3286 @Override 3287 @ParametricNullness 3288 public K firstKey() { 3289 // correctly throws NoSuchElementException when filtered map is empty. 3290 return keySet().iterator().next(); 3291 } 3292 3293 @Override 3294 @ParametricNullness 3295 public K lastKey() { 3296 SortedMap<K, V> headMap = sortedMap(); 3297 while (true) { 3298 // correctly throws NoSuchElementException when filtered map is empty. 3299 K key = headMap.lastKey(); 3300 // The cast is safe because the key is taken from the map. 3301 if (apply(key, uncheckedCastNullableTToT(unfiltered.get(key)))) { 3302 return key; 3303 } 3304 headMap = sortedMap().headMap(key); 3305 } 3306 } 3307 3308 @Override 3309 public SortedMap<K, V> headMap(@ParametricNullness K toKey) { 3310 return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate); 3311 } 3312 3313 @Override 3314 public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 3315 return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate); 3316 } 3317 3318 @Override 3319 public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { 3320 return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate); 3321 } 3322 } 3323 3324 @GwtIncompatible // NavigableMap 3325 private static class FilteredEntryNavigableMap< 3326 K extends @Nullable Object, V extends @Nullable Object> 3327 extends AbstractNavigableMap<K, V> { 3328 /* 3329 * It's less code to extend AbstractNavigableMap and forward the filtering logic to 3330 * FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap 3331 * methods. 3332 */ 3333 3334 private final NavigableMap<K, V> unfiltered; 3335 private final Predicate<? super Entry<K, V>> entryPredicate; 3336 private final Map<K, V> filteredDelegate; 3337 3338 FilteredEntryNavigableMap( 3339 NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 3340 this.unfiltered = checkNotNull(unfiltered); 3341 this.entryPredicate = entryPredicate; 3342 this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate); 3343 } 3344 3345 @Override 3346 @CheckForNull 3347 public Comparator<? super K> comparator() { 3348 return unfiltered.comparator(); 3349 } 3350 3351 @Override 3352 public NavigableSet<K> navigableKeySet() { 3353 return new Maps.NavigableKeySet<K, V>(this) { 3354 @Override 3355 public boolean removeAll(Collection<?> collection) { 3356 return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection); 3357 } 3358 3359 @Override 3360 public boolean retainAll(Collection<?> collection) { 3361 return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection); 3362 } 3363 }; 3364 } 3365 3366 @Override 3367 public Collection<V> values() { 3368 return new FilteredMapValues<>(this, unfiltered, entryPredicate); 3369 } 3370 3371 @Override 3372 Iterator<Entry<K, V>> entryIterator() { 3373 return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate); 3374 } 3375 3376 @Override 3377 Iterator<Entry<K, V>> descendingEntryIterator() { 3378 return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate); 3379 } 3380 3381 @Override 3382 public int size() { 3383 return filteredDelegate.size(); 3384 } 3385 3386 @Override 3387 public boolean isEmpty() { 3388 return !Iterables.any(unfiltered.entrySet(), entryPredicate); 3389 } 3390 3391 @Override 3392 @CheckForNull 3393 public V get(@CheckForNull Object key) { 3394 return filteredDelegate.get(key); 3395 } 3396 3397 @Override 3398 public boolean containsKey(@CheckForNull Object key) { 3399 return filteredDelegate.containsKey(key); 3400 } 3401 3402 @Override 3403 @CheckForNull 3404 public V put(@ParametricNullness K key, @ParametricNullness V value) { 3405 return filteredDelegate.put(key, value); 3406 } 3407 3408 @Override 3409 @CheckForNull 3410 public V remove(@CheckForNull Object key) { 3411 return filteredDelegate.remove(key); 3412 } 3413 3414 @Override 3415 public void putAll(Map<? extends K, ? extends V> m) { 3416 filteredDelegate.putAll(m); 3417 } 3418 3419 @Override 3420 public void clear() { 3421 filteredDelegate.clear(); 3422 } 3423 3424 @Override 3425 public Set<Entry<K, V>> entrySet() { 3426 return filteredDelegate.entrySet(); 3427 } 3428 3429 @Override 3430 @CheckForNull 3431 public Entry<K, V> pollFirstEntry() { 3432 return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate); 3433 } 3434 3435 @Override 3436 @CheckForNull 3437 public Entry<K, V> pollLastEntry() { 3438 return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate); 3439 } 3440 3441 @Override 3442 public NavigableMap<K, V> descendingMap() { 3443 return filterEntries(unfiltered.descendingMap(), entryPredicate); 3444 } 3445 3446 @Override 3447 public NavigableMap<K, V> subMap( 3448 @ParametricNullness K fromKey, 3449 boolean fromInclusive, 3450 @ParametricNullness K toKey, 3451 boolean toInclusive) { 3452 return filterEntries( 3453 unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate); 3454 } 3455 3456 @Override 3457 public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { 3458 return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate); 3459 } 3460 3461 @Override 3462 public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { 3463 return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate); 3464 } 3465 } 3466 3467 static final class FilteredEntryBiMap<K extends @Nullable Object, V extends @Nullable Object> 3468 extends FilteredEntryMap<K, V> implements BiMap<K, V> { 3469 @RetainedWith private final BiMap<V, K> inverse; 3470 3471 private static <K extends @Nullable Object, V extends @Nullable Object> 3472 Predicate<Entry<V, K>> inversePredicate( 3473 final Predicate<? super Entry<K, V>> forwardPredicate) { 3474 return new Predicate<Entry<V, K>>() { 3475 @Override 3476 public boolean apply(Entry<V, K> input) { 3477 return forwardPredicate.apply( 3478 Maps.<K, V>immutableEntry(input.getValue(), input.getKey())); 3479 } 3480 }; 3481 } 3482 3483 FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) { 3484 super(delegate, predicate); 3485 this.inverse = 3486 new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this); 3487 } 3488 3489 private FilteredEntryBiMap( 3490 BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) { 3491 super(delegate, predicate); 3492 this.inverse = inverse; 3493 } 3494 3495 BiMap<K, V> unfiltered() { 3496 return (BiMap<K, V>) unfiltered; 3497 } 3498 3499 @Override 3500 @CheckForNull 3501 public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { 3502 checkArgument(apply(key, value)); 3503 return unfiltered().forcePut(key, value); 3504 } 3505 3506 @Override 3507 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 3508 unfiltered() 3509 .replaceAll( 3510 (key, value) -> 3511 predicate.apply(Maps.<K, V>immutableEntry(key, value)) 3512 ? function.apply(key, value) 3513 : value); 3514 } 3515 3516 @Override 3517 public BiMap<V, K> inverse() { 3518 return inverse; 3519 } 3520 3521 @Override 3522 public Set<V> values() { 3523 return inverse.keySet(); 3524 } 3525 } 3526 3527 /** 3528 * Returns an unmodifiable view of the specified navigable map. Query operations on the returned 3529 * map read through to the specified map, and attempts to modify the returned map, whether direct 3530 * or via its views, result in an {@code UnsupportedOperationException}. 3531 * 3532 * <p>The returned navigable map will be serializable if the specified navigable map is 3533 * serializable. 3534 * 3535 * <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K, 3536 * V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code 3537 * comparator()} method might return a {@code Comparator<? extends K>}, which works only on a 3538 * particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which 3539 * must work on any type of {@code K}. 3540 * 3541 * @param map the navigable map for which an unmodifiable view is to be returned 3542 * @return an unmodifiable view of the specified navigable map 3543 * @since 12.0 3544 */ 3545 @GwtIncompatible // NavigableMap 3546 public static <K extends @Nullable Object, V extends @Nullable Object> 3547 NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) { 3548 checkNotNull(map); 3549 if (map instanceof UnmodifiableNavigableMap) { 3550 @SuppressWarnings("unchecked") // covariant 3551 NavigableMap<K, V> result = (NavigableMap<K, V>) map; 3552 return result; 3553 } else { 3554 return new UnmodifiableNavigableMap<>(map); 3555 } 3556 } 3557 3558 @CheckForNull 3559 private static <K extends @Nullable Object, V extends @Nullable Object> 3560 Entry<K, V> unmodifiableOrNull(@CheckForNull Entry<K, ? extends V> entry) { 3561 return (entry == null) ? null : Maps.unmodifiableEntry(entry); 3562 } 3563 3564 @GwtIncompatible // NavigableMap 3565 static class UnmodifiableNavigableMap<K extends @Nullable Object, V extends @Nullable Object> 3566 extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable { 3567 private final NavigableMap<K, ? extends V> delegate; 3568 3569 UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) { 3570 this.delegate = delegate; 3571 } 3572 3573 UnmodifiableNavigableMap( 3574 NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) { 3575 this.delegate = delegate; 3576 this.descendingMap = descendingMap; 3577 } 3578 3579 @Override 3580 protected SortedMap<K, V> delegate() { 3581 return Collections.unmodifiableSortedMap(delegate); 3582 } 3583 3584 @Override 3585 @CheckForNull 3586 public Entry<K, V> lowerEntry(@ParametricNullness K key) { 3587 return unmodifiableOrNull(delegate.lowerEntry(key)); 3588 } 3589 3590 @Override 3591 @CheckForNull 3592 public K lowerKey(@ParametricNullness K key) { 3593 return delegate.lowerKey(key); 3594 } 3595 3596 @Override 3597 @CheckForNull 3598 public Entry<K, V> floorEntry(@ParametricNullness K key) { 3599 return unmodifiableOrNull(delegate.floorEntry(key)); 3600 } 3601 3602 @Override 3603 @CheckForNull 3604 public K floorKey(@ParametricNullness K key) { 3605 return delegate.floorKey(key); 3606 } 3607 3608 @Override 3609 @CheckForNull 3610 public Entry<K, V> ceilingEntry(@ParametricNullness K key) { 3611 return unmodifiableOrNull(delegate.ceilingEntry(key)); 3612 } 3613 3614 @Override 3615 @CheckForNull 3616 public K ceilingKey(@ParametricNullness K key) { 3617 return delegate.ceilingKey(key); 3618 } 3619 3620 @Override 3621 @CheckForNull 3622 public Entry<K, V> higherEntry(@ParametricNullness K key) { 3623 return unmodifiableOrNull(delegate.higherEntry(key)); 3624 } 3625 3626 @Override 3627 @CheckForNull 3628 public K higherKey(@ParametricNullness K key) { 3629 return delegate.higherKey(key); 3630 } 3631 3632 @Override 3633 @CheckForNull 3634 public Entry<K, V> firstEntry() { 3635 return unmodifiableOrNull(delegate.firstEntry()); 3636 } 3637 3638 @Override 3639 @CheckForNull 3640 public Entry<K, V> lastEntry() { 3641 return unmodifiableOrNull(delegate.lastEntry()); 3642 } 3643 3644 @Override 3645 @CheckForNull 3646 public final Entry<K, V> pollFirstEntry() { 3647 throw new UnsupportedOperationException(); 3648 } 3649 3650 @Override 3651 @CheckForNull 3652 public final Entry<K, V> pollLastEntry() { 3653 throw new UnsupportedOperationException(); 3654 } 3655 3656 @Override 3657 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 3658 throw new UnsupportedOperationException(); 3659 } 3660 3661 @Override 3662 @CheckForNull 3663 public V putIfAbsent(K key, V value) { 3664 throw new UnsupportedOperationException(); 3665 } 3666 3667 @Override 3668 public boolean remove(@Nullable Object key, @Nullable Object value) { 3669 throw new UnsupportedOperationException(); 3670 } 3671 3672 @Override 3673 public boolean replace(K key, V oldValue, V newValue) { 3674 throw new UnsupportedOperationException(); 3675 } 3676 3677 @Override 3678 @CheckForNull 3679 public V replace(K key, V value) { 3680 throw new UnsupportedOperationException(); 3681 } 3682 3683 @Override 3684 public V computeIfAbsent( 3685 K key, java.util.function.Function<? super K, ? extends V> mappingFunction) { 3686 throw new UnsupportedOperationException(); 3687 } 3688 3689 /* 3690 * TODO(cpovirk): Uncomment the @NonNull annotations below once our JDK stubs and J2KT 3691 * emulations include them. 3692 */ 3693 @Override 3694 @CheckForNull 3695 /* 3696 * Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs. 3697 * But it doesn't, which may be a sign that we still permit parameter contravariance in some 3698 * cases? 3699 */ 3700 public V computeIfPresent( 3701 K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { 3702 throw new UnsupportedOperationException(); 3703 } 3704 3705 @Override 3706 @CheckForNull 3707 public V compute( 3708 K key, 3709 BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { 3710 throw new UnsupportedOperationException(); 3711 } 3712 3713 @Override 3714 @CheckForNull 3715 public V merge( 3716 K key, 3717 @NonNull V value, 3718 BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) { 3719 throw new UnsupportedOperationException(); 3720 } 3721 3722 @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap; 3723 3724 @Override 3725 public NavigableMap<K, V> descendingMap() { 3726 UnmodifiableNavigableMap<K, V> result = descendingMap; 3727 return (result == null) 3728 ? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this) 3729 : result; 3730 } 3731 3732 @Override 3733 public Set<K> keySet() { 3734 return navigableKeySet(); 3735 } 3736 3737 @Override 3738 public NavigableSet<K> navigableKeySet() { 3739 return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); 3740 } 3741 3742 @Override 3743 public NavigableSet<K> descendingKeySet() { 3744 return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); 3745 } 3746 3747 @Override 3748 public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 3749 return subMap(fromKey, true, toKey, false); 3750 } 3751 3752 @Override 3753 public NavigableMap<K, V> subMap( 3754 @ParametricNullness K fromKey, 3755 boolean fromInclusive, 3756 @ParametricNullness K toKey, 3757 boolean toInclusive) { 3758 return Maps.unmodifiableNavigableMap( 3759 delegate.subMap(fromKey, fromInclusive, toKey, toInclusive)); 3760 } 3761 3762 @Override 3763 public SortedMap<K, V> headMap(@ParametricNullness K toKey) { 3764 return headMap(toKey, false); 3765 } 3766 3767 @Override 3768 public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { 3769 return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); 3770 } 3771 3772 @Override 3773 public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { 3774 return tailMap(fromKey, true); 3775 } 3776 3777 @Override 3778 public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { 3779 return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); 3780 } 3781 } 3782 3783 /** 3784 * Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In 3785 * order to guarantee serial access, it is critical that <b>all</b> access to the backing 3786 * navigable map is accomplished through the returned navigable map (or its views). 3787 * 3788 * <p>It is imperative that the user manually synchronize on the returned navigable map when 3789 * iterating over any of its collection views, or the collections views of any of its {@code 3790 * descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views. 3791 * 3792 * <pre>{@code 3793 * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); 3794 * 3795 * // Needn't be in synchronized block 3796 * NavigableSet<K> set = map.navigableKeySet(); 3797 * 3798 * synchronized (map) { // Synchronizing on map, not set! 3799 * Iterator<K> it = set.iterator(); // Must be in synchronized block 3800 * while (it.hasNext()) { 3801 * foo(it.next()); 3802 * } 3803 * } 3804 * }</pre> 3805 * 3806 * <p>or: 3807 * 3808 * <pre>{@code 3809 * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); 3810 * NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true); 3811 * 3812 * // Needn't be in synchronized block 3813 * NavigableSet<K> set2 = map2.descendingKeySet(); 3814 * 3815 * synchronized (map) { // Synchronizing on map, not map2 or set2! 3816 * Iterator<K> it = set2.iterator(); // Must be in synchronized block 3817 * while (it.hasNext()) { 3818 * foo(it.next()); 3819 * } 3820 * } 3821 * }</pre> 3822 * 3823 * <p>Failure to follow this advice may result in non-deterministic behavior. 3824 * 3825 * <p>The returned navigable map will be serializable if the specified navigable map is 3826 * serializable. 3827 * 3828 * @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map. 3829 * @return a synchronized view of the specified navigable map. 3830 * @since 13.0 3831 */ 3832 @GwtIncompatible // NavigableMap 3833 @J2ktIncompatible // Synchronized 3834 public static <K extends @Nullable Object, V extends @Nullable Object> 3835 NavigableMap<K, V> synchronizedNavigableMap(NavigableMap<K, V> navigableMap) { 3836 return Synchronized.navigableMap(navigableMap); 3837 } 3838 3839 /** 3840 * {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and 3841 * entrySet views. 3842 */ 3843 @GwtCompatible 3844 abstract static class ViewCachingAbstractMap< 3845 K extends @Nullable Object, V extends @Nullable Object> 3846 extends AbstractMap<K, V> { 3847 /** 3848 * Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most 3849 * once on a given map, at the time when {@code entrySet} is first called. 3850 */ 3851 abstract Set<Entry<K, V>> createEntrySet(); 3852 3853 @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet; 3854 3855 @Override 3856 public Set<Entry<K, V>> entrySet() { 3857 Set<Entry<K, V>> result = entrySet; 3858 return (result == null) ? entrySet = createEntrySet() : result; 3859 } 3860 3861 @LazyInit @CheckForNull private transient Set<K> keySet; 3862 3863 @Override 3864 public Set<K> keySet() { 3865 Set<K> result = keySet; 3866 return (result == null) ? keySet = createKeySet() : result; 3867 } 3868 3869 Set<K> createKeySet() { 3870 return new KeySet<>(this); 3871 } 3872 3873 @LazyInit @CheckForNull private transient Collection<V> values; 3874 3875 @Override 3876 public Collection<V> values() { 3877 Collection<V> result = values; 3878 return (result == null) ? values = createValues() : result; 3879 } 3880 3881 Collection<V> createValues() { 3882 return new Values<>(this); 3883 } 3884 } 3885 3886 abstract static class IteratorBasedAbstractMap< 3887 K extends @Nullable Object, V extends @Nullable Object> 3888 extends AbstractMap<K, V> { 3889 @Override 3890 public abstract int size(); 3891 3892 abstract Iterator<Entry<K, V>> entryIterator(); 3893 3894 Spliterator<Entry<K, V>> entrySpliterator() { 3895 return Spliterators.spliterator( 3896 entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT); 3897 } 3898 3899 @Override 3900 public Set<Entry<K, V>> entrySet() { 3901 return new EntrySet<K, V>() { 3902 @Override 3903 Map<K, V> map() { 3904 return IteratorBasedAbstractMap.this; 3905 } 3906 3907 @Override 3908 public Iterator<Entry<K, V>> iterator() { 3909 return entryIterator(); 3910 } 3911 3912 @Override 3913 public Spliterator<Entry<K, V>> spliterator() { 3914 return entrySpliterator(); 3915 } 3916 3917 @Override 3918 public void forEach(Consumer<? super Entry<K, V>> action) { 3919 forEachEntry(action); 3920 } 3921 }; 3922 } 3923 3924 void forEachEntry(Consumer<? super Entry<K, V>> action) { 3925 entryIterator().forEachRemaining(action); 3926 } 3927 3928 @Override 3929 public void clear() { 3930 Iterators.clear(entryIterator()); 3931 } 3932 } 3933 3934 /** 3935 * Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code 3936 * NullPointerException}. 3937 */ 3938 @CheckForNull 3939 static <V extends @Nullable Object> V safeGet(Map<?, V> map, @CheckForNull Object key) { 3940 checkNotNull(map); 3941 try { 3942 return map.get(key); 3943 } catch (ClassCastException | NullPointerException e) { 3944 return null; 3945 } 3946 } 3947 3948 /** 3949 * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and 3950 * {@code NullPointerException}. 3951 */ 3952 static boolean safeContainsKey(Map<?, ?> map, @CheckForNull Object key) { 3953 checkNotNull(map); 3954 try { 3955 return map.containsKey(key); 3956 } catch (ClassCastException | NullPointerException e) { 3957 return false; 3958 } 3959 } 3960 3961 /** 3962 * Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code 3963 * NullPointerException}. 3964 */ 3965 @CheckForNull 3966 static <V extends @Nullable Object> V safeRemove(Map<?, V> map, @CheckForNull Object key) { 3967 checkNotNull(map); 3968 try { 3969 return map.remove(key); 3970 } catch (ClassCastException | NullPointerException e) { 3971 return null; 3972 } 3973 } 3974 3975 /** An admittedly inefficient implementation of {@link Map#containsKey}. */ 3976 static boolean containsKeyImpl(Map<?, ?> map, @CheckForNull Object key) { 3977 return Iterators.contains(keyIterator(map.entrySet().iterator()), key); 3978 } 3979 3980 /** An implementation of {@link Map#containsValue}. */ 3981 static boolean containsValueImpl(Map<?, ?> map, @CheckForNull Object value) { 3982 return Iterators.contains(valueIterator(map.entrySet().iterator()), value); 3983 } 3984 3985 /** 3986 * Implements {@code Collection.contains} safely for forwarding collections of map entries. If 3987 * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to 3988 * protect against a possible nefarious equals method. 3989 * 3990 * <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding 3991 * collection. 3992 * 3993 * @param c the delegate (unwrapped) collection of map entries 3994 * @param o the object that might be contained in {@code c} 3995 * @return {@code true} if {@code c} contains {@code o} 3996 */ 3997 static <K extends @Nullable Object, V extends @Nullable Object> boolean containsEntryImpl( 3998 Collection<Entry<K, V>> c, @CheckForNull Object o) { 3999 if (!(o instanceof Entry)) { 4000 return false; 4001 } 4002 return c.contains(unmodifiableEntry((Entry<?, ?>) o)); 4003 } 4004 4005 /** 4006 * Implements {@code Collection.remove} safely for forwarding collections of map entries. If 4007 * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to 4008 * protect against a possible nefarious equals method. 4009 * 4010 * <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection. 4011 * 4012 * @param c the delegate (unwrapped) collection of map entries 4013 * @param o the object to remove from {@code c} 4014 * @return {@code true} if {@code c} was changed 4015 */ 4016 static <K extends @Nullable Object, V extends @Nullable Object> boolean removeEntryImpl( 4017 Collection<Entry<K, V>> c, @CheckForNull Object o) { 4018 if (!(o instanceof Entry)) { 4019 return false; 4020 } 4021 return c.remove(unmodifiableEntry((Entry<?, ?>) o)); 4022 } 4023 4024 /** An implementation of {@link Map#equals}. */ 4025 static boolean equalsImpl(Map<?, ?> map, @CheckForNull Object object) { 4026 if (map == object) { 4027 return true; 4028 } else if (object instanceof Map) { 4029 Map<?, ?> o = (Map<?, ?>) object; 4030 return map.entrySet().equals(o.entrySet()); 4031 } 4032 return false; 4033 } 4034 4035 /** An implementation of {@link Map#toString}. */ 4036 static String toStringImpl(Map<?, ?> map) { 4037 StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{'); 4038 boolean first = true; 4039 for (Entry<?, ?> entry : map.entrySet()) { 4040 if (!first) { 4041 sb.append(", "); 4042 } 4043 first = false; 4044 sb.append(entry.getKey()).append('=').append(entry.getValue()); 4045 } 4046 return sb.append('}').toString(); 4047 } 4048 4049 /** An implementation of {@link Map#putAll}. */ 4050 static <K extends @Nullable Object, V extends @Nullable Object> void putAllImpl( 4051 Map<K, V> self, Map<? extends K, ? extends V> map) { 4052 for (Entry<? extends K, ? extends V> entry : map.entrySet()) { 4053 self.put(entry.getKey(), entry.getValue()); 4054 } 4055 } 4056 4057 static class KeySet<K extends @Nullable Object, V extends @Nullable Object> 4058 extends Sets.ImprovedAbstractSet<K> { 4059 @Weak final Map<K, V> map; 4060 4061 KeySet(Map<K, V> map) { 4062 this.map = checkNotNull(map); 4063 } 4064 4065 Map<K, V> map() { 4066 return map; 4067 } 4068 4069 @Override 4070 public Iterator<K> iterator() { 4071 return keyIterator(map().entrySet().iterator()); 4072 } 4073 4074 @Override 4075 public void forEach(Consumer<? super K> action) { 4076 checkNotNull(action); 4077 // avoids entry allocation for those maps that allocate entries on iteration 4078 map.forEach((k, v) -> action.accept(k)); 4079 } 4080 4081 @Override 4082 public int size() { 4083 return map().size(); 4084 } 4085 4086 @Override 4087 public boolean isEmpty() { 4088 return map().isEmpty(); 4089 } 4090 4091 @Override 4092 public boolean contains(@CheckForNull Object o) { 4093 return map().containsKey(o); 4094 } 4095 4096 @Override 4097 public boolean remove(@CheckForNull Object o) { 4098 if (contains(o)) { 4099 map().remove(o); 4100 return true; 4101 } 4102 return false; 4103 } 4104 4105 @Override 4106 public void clear() { 4107 map().clear(); 4108 } 4109 } 4110 4111 @CheckForNull 4112 static <K extends @Nullable Object> K keyOrNull(@CheckForNull Entry<K, ?> entry) { 4113 return (entry == null) ? null : entry.getKey(); 4114 } 4115 4116 @CheckForNull 4117 static <V extends @Nullable Object> V valueOrNull(@CheckForNull Entry<?, V> entry) { 4118 return (entry == null) ? null : entry.getValue(); 4119 } 4120 4121 static class SortedKeySet<K extends @Nullable Object, V extends @Nullable Object> 4122 extends KeySet<K, V> implements SortedSet<K> { 4123 SortedKeySet(SortedMap<K, V> map) { 4124 super(map); 4125 } 4126 4127 @Override 4128 SortedMap<K, V> map() { 4129 return (SortedMap<K, V>) super.map(); 4130 } 4131 4132 @Override 4133 @CheckForNull 4134 public Comparator<? super K> comparator() { 4135 return map().comparator(); 4136 } 4137 4138 @Override 4139 public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) { 4140 return new SortedKeySet<>(map().subMap(fromElement, toElement)); 4141 } 4142 4143 @Override 4144 public SortedSet<K> headSet(@ParametricNullness K toElement) { 4145 return new SortedKeySet<>(map().headMap(toElement)); 4146 } 4147 4148 @Override 4149 public SortedSet<K> tailSet(@ParametricNullness K fromElement) { 4150 return new SortedKeySet<>(map().tailMap(fromElement)); 4151 } 4152 4153 @Override 4154 @ParametricNullness 4155 public K first() { 4156 return map().firstKey(); 4157 } 4158 4159 @Override 4160 @ParametricNullness 4161 public K last() { 4162 return map().lastKey(); 4163 } 4164 } 4165 4166 @GwtIncompatible // NavigableMap 4167 static class NavigableKeySet<K extends @Nullable Object, V extends @Nullable Object> 4168 extends SortedKeySet<K, V> implements NavigableSet<K> { 4169 NavigableKeySet(NavigableMap<K, V> map) { 4170 super(map); 4171 } 4172 4173 @Override 4174 NavigableMap<K, V> map() { 4175 return (NavigableMap<K, V>) map; 4176 } 4177 4178 @Override 4179 @CheckForNull 4180 public K lower(@ParametricNullness K e) { 4181 return map().lowerKey(e); 4182 } 4183 4184 @Override 4185 @CheckForNull 4186 public K floor(@ParametricNullness K e) { 4187 return map().floorKey(e); 4188 } 4189 4190 @Override 4191 @CheckForNull 4192 public K ceiling(@ParametricNullness K e) { 4193 return map().ceilingKey(e); 4194 } 4195 4196 @Override 4197 @CheckForNull 4198 public K higher(@ParametricNullness K e) { 4199 return map().higherKey(e); 4200 } 4201 4202 @Override 4203 @CheckForNull 4204 public K pollFirst() { 4205 return keyOrNull(map().pollFirstEntry()); 4206 } 4207 4208 @Override 4209 @CheckForNull 4210 public K pollLast() { 4211 return keyOrNull(map().pollLastEntry()); 4212 } 4213 4214 @Override 4215 public NavigableSet<K> descendingSet() { 4216 return map().descendingKeySet(); 4217 } 4218 4219 @Override 4220 public Iterator<K> descendingIterator() { 4221 return descendingSet().iterator(); 4222 } 4223 4224 @Override 4225 public NavigableSet<K> subSet( 4226 @ParametricNullness K fromElement, 4227 boolean fromInclusive, 4228 @ParametricNullness K toElement, 4229 boolean toInclusive) { 4230 return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); 4231 } 4232 4233 @Override 4234 public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) { 4235 return subSet(fromElement, true, toElement, false); 4236 } 4237 4238 @Override 4239 public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) { 4240 return map().headMap(toElement, inclusive).navigableKeySet(); 4241 } 4242 4243 @Override 4244 public SortedSet<K> headSet(@ParametricNullness K toElement) { 4245 return headSet(toElement, false); 4246 } 4247 4248 @Override 4249 public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) { 4250 return map().tailMap(fromElement, inclusive).navigableKeySet(); 4251 } 4252 4253 @Override 4254 public SortedSet<K> tailSet(@ParametricNullness K fromElement) { 4255 return tailSet(fromElement, true); 4256 } 4257 } 4258 4259 static class Values<K extends @Nullable Object, V extends @Nullable Object> 4260 extends AbstractCollection<V> { 4261 @Weak final Map<K, V> map; 4262 4263 Values(Map<K, V> map) { 4264 this.map = checkNotNull(map); 4265 } 4266 4267 final Map<K, V> map() { 4268 return map; 4269 } 4270 4271 @Override 4272 public Iterator<V> iterator() { 4273 return valueIterator(map().entrySet().iterator()); 4274 } 4275 4276 @Override 4277 public void forEach(Consumer<? super V> action) { 4278 checkNotNull(action); 4279 // avoids allocation of entries for those maps that generate fresh entries on iteration 4280 map.forEach((k, v) -> action.accept(v)); 4281 } 4282 4283 @Override 4284 public boolean remove(@CheckForNull Object o) { 4285 try { 4286 return super.remove(o); 4287 } catch (UnsupportedOperationException e) { 4288 for (Entry<K, V> entry : map().entrySet()) { 4289 if (Objects.equal(o, entry.getValue())) { 4290 map().remove(entry.getKey()); 4291 return true; 4292 } 4293 } 4294 return false; 4295 } 4296 } 4297 4298 @Override 4299 public boolean removeAll(Collection<?> c) { 4300 try { 4301 return super.removeAll(checkNotNull(c)); 4302 } catch (UnsupportedOperationException e) { 4303 Set<K> toRemove = Sets.newHashSet(); 4304 for (Entry<K, V> entry : map().entrySet()) { 4305 if (c.contains(entry.getValue())) { 4306 toRemove.add(entry.getKey()); 4307 } 4308 } 4309 return map().keySet().removeAll(toRemove); 4310 } 4311 } 4312 4313 @Override 4314 public boolean retainAll(Collection<?> c) { 4315 try { 4316 return super.retainAll(checkNotNull(c)); 4317 } catch (UnsupportedOperationException e) { 4318 Set<K> toRetain = Sets.newHashSet(); 4319 for (Entry<K, V> entry : map().entrySet()) { 4320 if (c.contains(entry.getValue())) { 4321 toRetain.add(entry.getKey()); 4322 } 4323 } 4324 return map().keySet().retainAll(toRetain); 4325 } 4326 } 4327 4328 @Override 4329 public int size() { 4330 return map().size(); 4331 } 4332 4333 @Override 4334 public boolean isEmpty() { 4335 return map().isEmpty(); 4336 } 4337 4338 @Override 4339 public boolean contains(@CheckForNull Object o) { 4340 return map().containsValue(o); 4341 } 4342 4343 @Override 4344 public void clear() { 4345 map().clear(); 4346 } 4347 } 4348 4349 abstract static class EntrySet<K extends @Nullable Object, V extends @Nullable Object> 4350 extends Sets.ImprovedAbstractSet<Entry<K, V>> { 4351 abstract Map<K, V> map(); 4352 4353 @Override 4354 public int size() { 4355 return map().size(); 4356 } 4357 4358 @Override 4359 public void clear() { 4360 map().clear(); 4361 } 4362 4363 @Override 4364 public boolean contains(@CheckForNull Object o) { 4365 if (o instanceof Entry) { 4366 Entry<?, ?> entry = (Entry<?, ?>) o; 4367 Object key = entry.getKey(); 4368 V value = Maps.safeGet(map(), key); 4369 return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); 4370 } 4371 return false; 4372 } 4373 4374 @Override 4375 public boolean isEmpty() { 4376 return map().isEmpty(); 4377 } 4378 4379 @Override 4380 public boolean remove(@CheckForNull Object o) { 4381 /* 4382 * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our 4383 * nullness checker. 4384 */ 4385 if (contains(o) && o instanceof Entry) { 4386 Entry<?, ?> entry = (Entry<?, ?>) o; 4387 return map().keySet().remove(entry.getKey()); 4388 } 4389 return false; 4390 } 4391 4392 @Override 4393 public boolean removeAll(Collection<?> c) { 4394 try { 4395 return super.removeAll(checkNotNull(c)); 4396 } catch (UnsupportedOperationException e) { 4397 // if the iterators don't support remove 4398 return Sets.removeAllImpl(this, c.iterator()); 4399 } 4400 } 4401 4402 @Override 4403 public boolean retainAll(Collection<?> c) { 4404 try { 4405 return super.retainAll(checkNotNull(c)); 4406 } catch (UnsupportedOperationException e) { 4407 // if the iterators don't support remove 4408 Set<@Nullable Object> keys = Sets.newHashSetWithExpectedSize(c.size()); 4409 for (Object o : c) { 4410 /* 4411 * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our 4412 * nullness checker. 4413 */ 4414 if (contains(o) && o instanceof Entry) { 4415 Entry<?, ?> entry = (Entry<?, ?>) o; 4416 keys.add(entry.getKey()); 4417 } 4418 } 4419 return map().keySet().retainAll(keys); 4420 } 4421 } 4422 } 4423 4424 @GwtIncompatible // NavigableMap 4425 abstract static class DescendingMap<K extends @Nullable Object, V extends @Nullable Object> 4426 extends ForwardingMap<K, V> implements NavigableMap<K, V> { 4427 4428 abstract NavigableMap<K, V> forward(); 4429 4430 @Override 4431 protected final Map<K, V> delegate() { 4432 return forward(); 4433 } 4434 4435 @LazyInit @CheckForNull private transient Comparator<? super K> comparator; 4436 4437 @SuppressWarnings("unchecked") 4438 @Override 4439 public Comparator<? super K> comparator() { 4440 Comparator<? super K> result = comparator; 4441 if (result == null) { 4442 Comparator<? super K> forwardCmp = forward().comparator(); 4443 if (forwardCmp == null) { 4444 forwardCmp = (Comparator) Ordering.natural(); 4445 } 4446 result = comparator = reverse(forwardCmp); 4447 } 4448 return result; 4449 } 4450 4451 // If we inline this, we get a javac error. 4452 private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) { 4453 return Ordering.from(forward).reverse(); 4454 } 4455 4456 @Override 4457 @ParametricNullness 4458 public K firstKey() { 4459 return forward().lastKey(); 4460 } 4461 4462 @Override 4463 @ParametricNullness 4464 public K lastKey() { 4465 return forward().firstKey(); 4466 } 4467 4468 @Override 4469 @CheckForNull 4470 public Entry<K, V> lowerEntry(@ParametricNullness K key) { 4471 return forward().higherEntry(key); 4472 } 4473 4474 @Override 4475 @CheckForNull 4476 public K lowerKey(@ParametricNullness K key) { 4477 return forward().higherKey(key); 4478 } 4479 4480 @Override 4481 @CheckForNull 4482 public Entry<K, V> floorEntry(@ParametricNullness K key) { 4483 return forward().ceilingEntry(key); 4484 } 4485 4486 @Override 4487 @CheckForNull 4488 public K floorKey(@ParametricNullness K key) { 4489 return forward().ceilingKey(key); 4490 } 4491 4492 @Override 4493 @CheckForNull 4494 public Entry<K, V> ceilingEntry(@ParametricNullness K key) { 4495 return forward().floorEntry(key); 4496 } 4497 4498 @Override 4499 @CheckForNull 4500 public K ceilingKey(@ParametricNullness K key) { 4501 return forward().floorKey(key); 4502 } 4503 4504 @Override 4505 @CheckForNull 4506 public Entry<K, V> higherEntry(@ParametricNullness K key) { 4507 return forward().lowerEntry(key); 4508 } 4509 4510 @Override 4511 @CheckForNull 4512 public K higherKey(@ParametricNullness K key) { 4513 return forward().lowerKey(key); 4514 } 4515 4516 @Override 4517 @CheckForNull 4518 public Entry<K, V> firstEntry() { 4519 return forward().lastEntry(); 4520 } 4521 4522 @Override 4523 @CheckForNull 4524 public Entry<K, V> lastEntry() { 4525 return forward().firstEntry(); 4526 } 4527 4528 @Override 4529 @CheckForNull 4530 public Entry<K, V> pollFirstEntry() { 4531 return forward().pollLastEntry(); 4532 } 4533 4534 @Override 4535 @CheckForNull 4536 public Entry<K, V> pollLastEntry() { 4537 return forward().pollFirstEntry(); 4538 } 4539 4540 @Override 4541 public NavigableMap<K, V> descendingMap() { 4542 return forward(); 4543 } 4544 4545 @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet; 4546 4547 @Override 4548 public Set<Entry<K, V>> entrySet() { 4549 Set<Entry<K, V>> result = entrySet; 4550 return (result == null) ? entrySet = createEntrySet() : result; 4551 } 4552 4553 abstract Iterator<Entry<K, V>> entryIterator(); 4554 4555 Set<Entry<K, V>> createEntrySet() { 4556 @WeakOuter 4557 class EntrySetImpl extends EntrySet<K, V> { 4558 @Override 4559 Map<K, V> map() { 4560 return DescendingMap.this; 4561 } 4562 4563 @Override 4564 public Iterator<Entry<K, V>> iterator() { 4565 return entryIterator(); 4566 } 4567 } 4568 return new EntrySetImpl(); 4569 } 4570 4571 @Override 4572 public Set<K> keySet() { 4573 return navigableKeySet(); 4574 } 4575 4576 @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet; 4577 4578 @Override 4579 public NavigableSet<K> navigableKeySet() { 4580 NavigableSet<K> result = navigableKeySet; 4581 return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result; 4582 } 4583 4584 @Override 4585 public NavigableSet<K> descendingKeySet() { 4586 return forward().navigableKeySet(); 4587 } 4588 4589 @Override 4590 public NavigableMap<K, V> subMap( 4591 @ParametricNullness K fromKey, 4592 boolean fromInclusive, 4593 @ParametricNullness K toKey, 4594 boolean toInclusive) { 4595 return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); 4596 } 4597 4598 @Override 4599 public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { 4600 return subMap(fromKey, true, toKey, false); 4601 } 4602 4603 @Override 4604 public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { 4605 return forward().tailMap(toKey, inclusive).descendingMap(); 4606 } 4607 4608 @Override 4609 public SortedMap<K, V> headMap(@ParametricNullness K toKey) { 4610 return headMap(toKey, false); 4611 } 4612 4613 @Override 4614 public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { 4615 return forward().headMap(fromKey, inclusive).descendingMap(); 4616 } 4617 4618 @Override 4619 public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { 4620 return tailMap(fromKey, true); 4621 } 4622 4623 @Override 4624 public Collection<V> values() { 4625 return new Values<>(this); 4626 } 4627 4628 @Override 4629 public String toString() { 4630 return standardToString(); 4631 } 4632 } 4633 4634 /** Returns a map from the ith element of list to i. */ 4635 static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) { 4636 ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size()); 4637 int i = 0; 4638 for (E e : list) { 4639 builder.put(e, i++); 4640 } 4641 return builder.buildOrThrow(); 4642 } 4643 4644 /** 4645 * Returns a view of the portion of {@code map} whose keys are contained by {@code range}. 4646 * 4647 * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link 4648 * NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link 4649 * NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object, 4650 * boolean) headMap()}) to actually construct the view. Consult these methods for a full 4651 * description of the returned view's behavior. 4652 * 4653 * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural 4654 * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link 4655 * Comparator}, which can violate the natural ordering. Using this method (or in general using 4656 * {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior. 4657 * 4658 * @since 20.0 4659 */ 4660 @GwtIncompatible // NavigableMap 4661 public static <K extends Comparable<? super K>, V extends @Nullable Object> 4662 NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) { 4663 if (map.comparator() != null 4664 && map.comparator() != Ordering.natural() 4665 && range.hasLowerBound() 4666 && range.hasUpperBound()) { 4667 checkArgument( 4668 map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, 4669 "map is using a custom comparator which is inconsistent with the natural ordering."); 4670 } 4671 if (range.hasLowerBound() && range.hasUpperBound()) { 4672 return map.subMap( 4673 range.lowerEndpoint(), 4674 range.lowerBoundType() == BoundType.CLOSED, 4675 range.upperEndpoint(), 4676 range.upperBoundType() == BoundType.CLOSED); 4677 } else if (range.hasLowerBound()) { 4678 return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); 4679 } else if (range.hasUpperBound()) { 4680 return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); 4681 } 4682 return checkNotNull(map); 4683 } 4684}