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