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