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