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