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.checkNotNull; 020import static com.google.common.collect.CollectPreconditions.checkNonnegative; 021import static com.google.common.collect.CollectPreconditions.checkRemove; 022 023import com.google.common.annotations.Beta; 024import com.google.common.annotations.GwtCompatible; 025import com.google.common.annotations.GwtIncompatible; 026import com.google.common.base.Function; 027import com.google.common.base.Predicate; 028import com.google.common.base.Predicates; 029import com.google.common.base.Supplier; 030import com.google.common.collect.AbstractMultimap.Entries; 031import com.google.common.collect.AbstractMultimap.EntrySet; 032import com.google.common.collect.Maps.EntryTransformer; 033import com.google.errorprone.annotations.CanIgnoreReturnValue; 034import com.google.j2objc.annotations.Weak; 035import com.google.j2objc.annotations.WeakOuter; 036import java.io.IOException; 037import java.io.ObjectInputStream; 038import java.io.ObjectOutputStream; 039import java.io.Serializable; 040import java.util.AbstractCollection; 041import java.util.Collection; 042import java.util.Collections; 043import java.util.Comparator; 044import java.util.HashSet; 045import java.util.Iterator; 046import java.util.List; 047import java.util.Map; 048import java.util.Map.Entry; 049import java.util.NoSuchElementException; 050import java.util.Set; 051import java.util.SortedSet; 052import java.util.Spliterator; 053import java.util.function.Consumer; 054import java.util.stream.Collector; 055import java.util.stream.Stream; 056import org.checkerframework.checker.nullness.compatqual.NullableDecl; 057 058/** 059 * Provides static methods acting on or generating a {@code Multimap}. 060 * 061 * <p>See the Guava User Guide article on <a href= 062 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multimaps"> {@code 063 * Multimaps}</a>. 064 * 065 * @author Jared Levy 066 * @author Robert Konigsberg 067 * @author Mike Bostock 068 * @author Louis Wasserman 069 * @since 2.0 070 */ 071@GwtCompatible(emulated = true) 072public final class Multimaps { 073 private Multimaps() {} 074 075 /** 076 * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the 077 * specified supplier. The keys and values of the entries are the result of applying the provided 078 * mapping functions to the input elements, accumulated in the encounter order of the stream. 079 * 080 * <p>Example: 081 * 082 * <pre>{@code 083 * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP = 084 * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") 085 * .collect( 086 * toMultimap( 087 * str -> str.charAt(0), 088 * str -> str.substring(1), 089 * MultimapBuilder.treeKeys().arrayListValues()::build)); 090 * 091 * // is equivalent to 092 * 093 * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP; 094 * 095 * static { 096 * FIRST_LETTER_MULTIMAP = MultimapBuilder.treeKeys().arrayListValues().build(); 097 * FIRST_LETTER_MULTIMAP.put('b', "anana"); 098 * FIRST_LETTER_MULTIMAP.put('a', "pple"); 099 * FIRST_LETTER_MULTIMAP.put('a', "sparagus"); 100 * FIRST_LETTER_MULTIMAP.put('c', "arrot"); 101 * FIRST_LETTER_MULTIMAP.put('c', "herry"); 102 * } 103 * }</pre> 104 * 105 * @since 21.0 106 */ 107 @Beta 108 public static <T, K, V, M extends Multimap<K, V>> Collector<T, ?, M> toMultimap( 109 java.util.function.Function<? super T, ? extends K> keyFunction, 110 java.util.function.Function<? super T, ? extends V> valueFunction, 111 java.util.function.Supplier<M> multimapSupplier) { 112 checkNotNull(keyFunction); 113 checkNotNull(valueFunction); 114 checkNotNull(multimapSupplier); 115 return Collector.of( 116 multimapSupplier, 117 (multimap, input) -> multimap.put(keyFunction.apply(input), valueFunction.apply(input)), 118 (multimap1, multimap2) -> { 119 multimap1.putAll(multimap2); 120 return multimap1; 121 }); 122 } 123 124 /** 125 * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the 126 * specified supplier. Each input element is mapped to a key and a stream of values, each of which 127 * are put into the resulting {@code Multimap}, in the encounter order of the stream and the 128 * encounter order of the streams of values. 129 * 130 * <p>Example: 131 * 132 * <pre>{@code 133 * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP = 134 * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") 135 * .collect( 136 * flatteningToMultimap( 137 * str -> str.charAt(0), 138 * str -> str.substring(1).chars().mapToObj(c -> (char) c), 139 * MultimapBuilder.linkedHashKeys().arrayListValues()::build)); 140 * 141 * // is equivalent to 142 * 143 * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP; 144 * 145 * static { 146 * FIRST_LETTER_MULTIMAP = MultimapBuilder.linkedHashKeys().arrayListValues().build(); 147 * FIRST_LETTER_MULTIMAP.putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')); 148 * FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('p', 'p', 'l', 'e')); 149 * FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')); 150 * FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')); 151 * FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')); 152 * } 153 * }</pre> 154 * 155 * @since 21.0 156 */ 157 @Beta 158 public static <T, K, V, M extends Multimap<K, V>> Collector<T, ?, M> flatteningToMultimap( 159 java.util.function.Function<? super T, ? extends K> keyFunction, 160 java.util.function.Function<? super T, ? extends Stream<? extends V>> valueFunction, 161 java.util.function.Supplier<M> multimapSupplier) { 162 checkNotNull(keyFunction); 163 checkNotNull(valueFunction); 164 checkNotNull(multimapSupplier); 165 return Collector.of( 166 multimapSupplier, 167 (multimap, input) -> { 168 K key = keyFunction.apply(input); 169 Collection<V> valuesForKey = multimap.get(key); 170 valueFunction.apply(input).forEachOrdered(valuesForKey::add); 171 }, 172 (multimap1, multimap2) -> { 173 multimap1.putAll(multimap2); 174 return multimap1; 175 }); 176 } 177 178 /** 179 * Creates a new {@code Multimap} backed by {@code map}, whose internal value collections are 180 * generated by {@code factory}. 181 * 182 * <p><b>Warning: do not use</b> this method when the collections returned by {@code factory} 183 * implement either {@link List} or {@code Set}! Use the more specific method {@link 184 * #newListMultimap}, {@link #newSetMultimap} or {@link #newSortedSetMultimap} instead, to avoid 185 * very surprising behavior from {@link Multimap#equals}. 186 * 187 * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration 188 * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code 189 * toString} methods for the multimap and its returned views. However, the multimap's {@code get} 190 * method returns instances of a different class than {@code factory.get()} does. 191 * 192 * <p>The multimap is serializable if {@code map}, {@code factory}, the collections generated by 193 * {@code factory}, and the multimap contents are all serializable. 194 * 195 * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if 196 * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will 197 * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link 198 * #synchronizedMultimap}. 199 * 200 * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()}, {@link 201 * HashMultimap#create()}, {@link LinkedHashMultimap#create()}, {@link 202 * LinkedListMultimap#create()}, {@link TreeMultimap#create()}, and {@link 203 * TreeMultimap#create(Comparator, Comparator)} won't suffice. 204 * 205 * <p>Note: the multimap assumes complete ownership over of {@code map} and the collections 206 * returned by {@code factory}. Those objects should not be manually updated and they should not 207 * use soft, weak, or phantom references. 208 * 209 * @param map place to store the mapping from each key to its corresponding values 210 * @param factory supplier of new, empty collections that will each hold all values for a given 211 * key 212 * @throws IllegalArgumentException if {@code map} is not empty 213 */ 214 public static <K, V> Multimap<K, V> newMultimap( 215 Map<K, Collection<V>> map, final Supplier<? extends Collection<V>> factory) { 216 return new CustomMultimap<>(map, factory); 217 } 218 219 private static class CustomMultimap<K, V> extends AbstractMapBasedMultimap<K, V> { 220 transient Supplier<? extends Collection<V>> factory; 221 222 CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) { 223 super(map); 224 this.factory = checkNotNull(factory); 225 } 226 227 @Override 228 protected Collection<V> createCollection() { 229 return factory.get(); 230 } 231 232 // can't use Serialization writeMultimap and populateMultimap methods since 233 // there's no way to generate the empty backing map. 234 235 /** @serialData the factory and the backing map */ 236 @GwtIncompatible // java.io.ObjectOutputStream 237 private void writeObject(ObjectOutputStream stream) throws IOException { 238 stream.defaultWriteObject(); 239 stream.writeObject(factory); 240 stream.writeObject(backingMap()); 241 } 242 243 @GwtIncompatible // java.io.ObjectInputStream 244 @SuppressWarnings("unchecked") // reading data stored by writeObject 245 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 246 stream.defaultReadObject(); 247 factory = (Supplier<? extends Collection<V>>) stream.readObject(); 248 Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); 249 setMap(map); 250 } 251 252 @GwtIncompatible // java serialization not supported 253 private static final long serialVersionUID = 0; 254 } 255 256 /** 257 * Creates a new {@code ListMultimap} that uses the provided map and factory. It can generate a 258 * multimap based on arbitrary {@link Map} and {@link List} classes. 259 * 260 * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration 261 * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code 262 * toString} methods for the multimap and its returned views. The multimap's {@code get}, {@code 263 * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} lists if the factory 264 * does. However, the multimap's {@code get} method returns instances of a different class than 265 * does {@code factory.get()}. 266 * 267 * <p>The multimap is serializable if {@code map}, {@code factory}, the lists generated by {@code 268 * factory}, and the multimap contents are all serializable. 269 * 270 * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if 271 * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will 272 * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link 273 * #synchronizedListMultimap}. 274 * 275 * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()} and {@link 276 * LinkedListMultimap#create()} won't suffice. 277 * 278 * <p>Note: the multimap assumes complete ownership over of {@code map} and the lists returned by 279 * {@code factory}. Those objects should not be manually updated, they should be empty when 280 * provided, and they should not use soft, weak, or phantom references. 281 * 282 * @param map place to store the mapping from each key to its corresponding values 283 * @param factory supplier of new, empty lists that will each hold all values for a given key 284 * @throws IllegalArgumentException if {@code map} is not empty 285 */ 286 public static <K, V> ListMultimap<K, V> newListMultimap( 287 Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) { 288 return new CustomListMultimap<>(map, factory); 289 } 290 291 private static class CustomListMultimap<K, V> extends AbstractListMultimap<K, V> { 292 transient Supplier<? extends List<V>> factory; 293 294 CustomListMultimap(Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) { 295 super(map); 296 this.factory = checkNotNull(factory); 297 } 298 299 @Override 300 protected List<V> createCollection() { 301 return factory.get(); 302 } 303 304 /** @serialData the factory and the backing map */ 305 @GwtIncompatible // java.io.ObjectOutputStream 306 private void writeObject(ObjectOutputStream stream) throws IOException { 307 stream.defaultWriteObject(); 308 stream.writeObject(factory); 309 stream.writeObject(backingMap()); 310 } 311 312 @GwtIncompatible // java.io.ObjectInputStream 313 @SuppressWarnings("unchecked") // reading data stored by writeObject 314 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 315 stream.defaultReadObject(); 316 factory = (Supplier<? extends List<V>>) stream.readObject(); 317 Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); 318 setMap(map); 319 } 320 321 @GwtIncompatible // java serialization not supported 322 private static final long serialVersionUID = 0; 323 } 324 325 /** 326 * Creates a new {@code SetMultimap} that uses the provided map and factory. It can generate a 327 * multimap based on arbitrary {@link Map} and {@link Set} classes. 328 * 329 * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration 330 * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code 331 * toString} methods for the multimap and its returned views. However, the multimap's {@code get} 332 * method returns instances of a different class than {@code factory.get()} does. 333 * 334 * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code 335 * factory}, and the multimap contents are all serializable. 336 * 337 * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if 338 * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will 339 * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link 340 * #synchronizedSetMultimap}. 341 * 342 * <p>Call this method only when the simpler methods {@link HashMultimap#create()}, {@link 343 * LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and {@link 344 * TreeMultimap#create(Comparator, Comparator)} won't suffice. 345 * 346 * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by 347 * {@code factory}. Those objects should not be manually updated and they should not use soft, 348 * weak, or phantom references. 349 * 350 * @param map place to store the mapping from each key to its corresponding values 351 * @param factory supplier of new, empty sets that will each hold all values for a given key 352 * @throws IllegalArgumentException if {@code map} is not empty 353 */ 354 public static <K, V> SetMultimap<K, V> newSetMultimap( 355 Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) { 356 return new CustomSetMultimap<>(map, factory); 357 } 358 359 private static class CustomSetMultimap<K, V> extends AbstractSetMultimap<K, V> { 360 transient Supplier<? extends Set<V>> factory; 361 362 CustomSetMultimap(Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) { 363 super(map); 364 this.factory = checkNotNull(factory); 365 } 366 367 @Override 368 protected Set<V> createCollection() { 369 return factory.get(); 370 } 371 372 /** @serialData the factory and the backing map */ 373 @GwtIncompatible // java.io.ObjectOutputStream 374 private void writeObject(ObjectOutputStream stream) throws IOException { 375 stream.defaultWriteObject(); 376 stream.writeObject(factory); 377 stream.writeObject(backingMap()); 378 } 379 380 @GwtIncompatible // java.io.ObjectInputStream 381 @SuppressWarnings("unchecked") // reading data stored by writeObject 382 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 383 stream.defaultReadObject(); 384 factory = (Supplier<? extends Set<V>>) stream.readObject(); 385 Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); 386 setMap(map); 387 } 388 389 @GwtIncompatible // not needed in emulated source 390 private static final long serialVersionUID = 0; 391 } 392 393 /** 394 * Creates a new {@code SortedSetMultimap} that uses the provided map and factory. It can generate 395 * a multimap based on arbitrary {@link Map} and {@link SortedSet} classes. 396 * 397 * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration 398 * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code 399 * toString} methods for the multimap and its returned views. However, the multimap's {@code get} 400 * method returns instances of a different class than {@code factory.get()} does. 401 * 402 * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code 403 * factory}, and the multimap contents are all serializable. 404 * 405 * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if 406 * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will 407 * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link 408 * #synchronizedSortedSetMultimap}. 409 * 410 * <p>Call this method only when the simpler methods {@link TreeMultimap#create()} and {@link 411 * TreeMultimap#create(Comparator, Comparator)} won't suffice. 412 * 413 * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by 414 * {@code factory}. Those objects should not be manually updated and they should not use soft, 415 * weak, or phantom references. 416 * 417 * @param map place to store the mapping from each key to its corresponding values 418 * @param factory supplier of new, empty sorted sets that will each hold all values for a given 419 * key 420 * @throws IllegalArgumentException if {@code map} is not empty 421 */ 422 public static <K, V> SortedSetMultimap<K, V> newSortedSetMultimap( 423 Map<K, Collection<V>> map, final Supplier<? extends SortedSet<V>> factory) { 424 return new CustomSortedSetMultimap<>(map, factory); 425 } 426 427 private static class CustomSortedSetMultimap<K, V> extends AbstractSortedSetMultimap<K, V> { 428 transient Supplier<? extends SortedSet<V>> factory; 429 transient Comparator<? super V> valueComparator; 430 431 CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) { 432 super(map); 433 this.factory = checkNotNull(factory); 434 valueComparator = factory.get().comparator(); 435 } 436 437 @Override 438 protected SortedSet<V> createCollection() { 439 return factory.get(); 440 } 441 442 @Override 443 public Comparator<? super V> valueComparator() { 444 return valueComparator; 445 } 446 447 /** @serialData the factory and the backing map */ 448 @GwtIncompatible // java.io.ObjectOutputStream 449 private void writeObject(ObjectOutputStream stream) throws IOException { 450 stream.defaultWriteObject(); 451 stream.writeObject(factory); 452 stream.writeObject(backingMap()); 453 } 454 455 @GwtIncompatible // java.io.ObjectInputStream 456 @SuppressWarnings("unchecked") // reading data stored by writeObject 457 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 458 stream.defaultReadObject(); 459 factory = (Supplier<? extends SortedSet<V>>) stream.readObject(); 460 valueComparator = factory.get().comparator(); 461 Map<K, Collection<V>> map = (Map<K, Collection<V>>) stream.readObject(); 462 setMap(map); 463 } 464 465 @GwtIncompatible // not needed in emulated source 466 private static final long serialVersionUID = 0; 467 } 468 469 /** 470 * Copies each key-value mapping in {@code source} into {@code dest}, with its key and value 471 * reversed. 472 * 473 * <p>If {@code source} is an {@link ImmutableMultimap}, consider using {@link 474 * ImmutableMultimap#inverse} instead. 475 * 476 * @param source any multimap 477 * @param dest the multimap to copy into; usually empty 478 * @return {@code dest} 479 */ 480 @CanIgnoreReturnValue 481 public static <K, V, M extends Multimap<K, V>> M invertFrom( 482 Multimap<? extends V, ? extends K> source, M dest) { 483 checkNotNull(dest); 484 for (Map.Entry<? extends V, ? extends K> entry : source.entries()) { 485 dest.put(entry.getValue(), entry.getKey()); 486 } 487 return dest; 488 } 489 490 /** 491 * Returns a synchronized (thread-safe) multimap backed by the specified multimap. In order to 492 * guarantee serial access, it is critical that <b>all</b> access to the backing multimap is 493 * accomplished through the returned multimap. 494 * 495 * <p>It is imperative that the user manually synchronize on the returned multimap when accessing 496 * any of its collection views: 497 * 498 * <pre>{@code 499 * Multimap<K, V> multimap = Multimaps.synchronizedMultimap( 500 * HashMultimap.<K, V>create()); 501 * ... 502 * Collection<V> values = multimap.get(key); // Needn't be in synchronized block 503 * ... 504 * synchronized (multimap) { // Synchronizing on multimap, not values! 505 * Iterator<V> i = values.iterator(); // Must be in synchronized block 506 * while (i.hasNext()) { 507 * foo(i.next()); 508 * } 509 * } 510 * }</pre> 511 * 512 * <p>Failure to follow this advice may result in non-deterministic behavior. 513 * 514 * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link 515 * Multimap#replaceValues} methods return collections that aren't synchronized. 516 * 517 * <p>The returned multimap will be serializable if the specified multimap is serializable. 518 * 519 * @param multimap the multimap to be wrapped in a synchronized view 520 * @return a synchronized view of the specified multimap 521 */ 522 public static <K, V> Multimap<K, V> synchronizedMultimap(Multimap<K, V> multimap) { 523 return Synchronized.multimap(multimap, null); 524 } 525 526 /** 527 * Returns an unmodifiable view of the specified multimap. Query operations on the returned 528 * multimap "read through" to the specified multimap, and attempts to modify the returned 529 * multimap, either directly or through the multimap's views, result in an {@code 530 * UnsupportedOperationException}. 531 * 532 * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link 533 * Multimap#replaceValues} methods return collections that are modifiable. 534 * 535 * <p>The returned multimap will be serializable if the specified multimap is serializable. 536 * 537 * @param delegate the multimap for which an unmodifiable view is to be returned 538 * @return an unmodifiable view of the specified multimap 539 */ 540 public static <K, V> Multimap<K, V> unmodifiableMultimap(Multimap<K, V> delegate) { 541 if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { 542 return delegate; 543 } 544 return new UnmodifiableMultimap<>(delegate); 545 } 546 547 /** 548 * Simply returns its argument. 549 * 550 * @deprecated no need to use this 551 * @since 10.0 552 */ 553 @Deprecated 554 public static <K, V> Multimap<K, V> unmodifiableMultimap(ImmutableMultimap<K, V> delegate) { 555 return checkNotNull(delegate); 556 } 557 558 private static class UnmodifiableMultimap<K, V> extends ForwardingMultimap<K, V> 559 implements Serializable { 560 final Multimap<K, V> delegate; 561 transient Collection<Entry<K, V>> entries; 562 transient Multiset<K> keys; 563 transient Set<K> keySet; 564 transient Collection<V> values; 565 transient Map<K, Collection<V>> map; 566 567 UnmodifiableMultimap(final Multimap<K, V> delegate) { 568 this.delegate = checkNotNull(delegate); 569 } 570 571 @Override 572 protected Multimap<K, V> delegate() { 573 return delegate; 574 } 575 576 @Override 577 public void clear() { 578 throw new UnsupportedOperationException(); 579 } 580 581 @Override 582 public Map<K, Collection<V>> asMap() { 583 Map<K, Collection<V>> result = map; 584 if (result == null) { 585 result = 586 map = 587 Collections.unmodifiableMap( 588 Maps.transformValues( 589 delegate.asMap(), 590 new Function<Collection<V>, Collection<V>>() { 591 @Override 592 public Collection<V> apply(Collection<V> collection) { 593 return unmodifiableValueCollection(collection); 594 } 595 })); 596 } 597 return result; 598 } 599 600 @Override 601 public Collection<Entry<K, V>> entries() { 602 Collection<Entry<K, V>> result = entries; 603 if (result == null) { 604 entries = result = unmodifiableEntries(delegate.entries()); 605 } 606 return result; 607 } 608 609 @Override 610 public Collection<V> get(K key) { 611 return unmodifiableValueCollection(delegate.get(key)); 612 } 613 614 @Override 615 public Multiset<K> keys() { 616 Multiset<K> result = keys; 617 if (result == null) { 618 keys = result = Multisets.unmodifiableMultiset(delegate.keys()); 619 } 620 return result; 621 } 622 623 @Override 624 public Set<K> keySet() { 625 Set<K> result = keySet; 626 if (result == null) { 627 keySet = result = Collections.unmodifiableSet(delegate.keySet()); 628 } 629 return result; 630 } 631 632 @Override 633 public boolean put(K key, V value) { 634 throw new UnsupportedOperationException(); 635 } 636 637 @Override 638 public boolean putAll(K key, Iterable<? extends V> values) { 639 throw new UnsupportedOperationException(); 640 } 641 642 @Override 643 public boolean putAll(Multimap<? extends K, ? extends V> multimap) { 644 throw new UnsupportedOperationException(); 645 } 646 647 @Override 648 public boolean remove(Object key, Object value) { 649 throw new UnsupportedOperationException(); 650 } 651 652 @Override 653 public Collection<V> removeAll(Object key) { 654 throw new UnsupportedOperationException(); 655 } 656 657 @Override 658 public Collection<V> replaceValues(K key, Iterable<? extends V> values) { 659 throw new UnsupportedOperationException(); 660 } 661 662 @Override 663 public Collection<V> values() { 664 Collection<V> result = values; 665 if (result == null) { 666 values = result = Collections.unmodifiableCollection(delegate.values()); 667 } 668 return result; 669 } 670 671 private static final long serialVersionUID = 0; 672 } 673 674 private static class UnmodifiableListMultimap<K, V> extends UnmodifiableMultimap<K, V> 675 implements ListMultimap<K, V> { 676 UnmodifiableListMultimap(ListMultimap<K, V> delegate) { 677 super(delegate); 678 } 679 680 @Override 681 public ListMultimap<K, V> delegate() { 682 return (ListMultimap<K, V>) super.delegate(); 683 } 684 685 @Override 686 public List<V> get(K key) { 687 return Collections.unmodifiableList(delegate().get(key)); 688 } 689 690 @Override 691 public List<V> removeAll(Object key) { 692 throw new UnsupportedOperationException(); 693 } 694 695 @Override 696 public List<V> replaceValues(K key, Iterable<? extends V> values) { 697 throw new UnsupportedOperationException(); 698 } 699 700 private static final long serialVersionUID = 0; 701 } 702 703 private static class UnmodifiableSetMultimap<K, V> extends UnmodifiableMultimap<K, V> 704 implements SetMultimap<K, V> { 705 UnmodifiableSetMultimap(SetMultimap<K, V> delegate) { 706 super(delegate); 707 } 708 709 @Override 710 public SetMultimap<K, V> delegate() { 711 return (SetMultimap<K, V>) super.delegate(); 712 } 713 714 @Override 715 public Set<V> get(K key) { 716 /* 717 * Note that this doesn't return a SortedSet when delegate is a 718 * SortedSetMultiset, unlike (SortedSet<V>) super.get(). 719 */ 720 return Collections.unmodifiableSet(delegate().get(key)); 721 } 722 723 @Override 724 public Set<Map.Entry<K, V>> entries() { 725 return Maps.unmodifiableEntrySet(delegate().entries()); 726 } 727 728 @Override 729 public Set<V> removeAll(Object key) { 730 throw new UnsupportedOperationException(); 731 } 732 733 @Override 734 public Set<V> replaceValues(K key, Iterable<? extends V> values) { 735 throw new UnsupportedOperationException(); 736 } 737 738 private static final long serialVersionUID = 0; 739 } 740 741 private static class UnmodifiableSortedSetMultimap<K, V> extends UnmodifiableSetMultimap<K, V> 742 implements SortedSetMultimap<K, V> { 743 UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) { 744 super(delegate); 745 } 746 747 @Override 748 public SortedSetMultimap<K, V> delegate() { 749 return (SortedSetMultimap<K, V>) super.delegate(); 750 } 751 752 @Override 753 public SortedSet<V> get(K key) { 754 return Collections.unmodifiableSortedSet(delegate().get(key)); 755 } 756 757 @Override 758 public SortedSet<V> removeAll(Object key) { 759 throw new UnsupportedOperationException(); 760 } 761 762 @Override 763 public SortedSet<V> replaceValues(K key, Iterable<? extends V> values) { 764 throw new UnsupportedOperationException(); 765 } 766 767 @Override 768 public Comparator<? super V> valueComparator() { 769 return delegate().valueComparator(); 770 } 771 772 private static final long serialVersionUID = 0; 773 } 774 775 /** 776 * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the specified multimap. 777 * 778 * <p>You must follow the warnings described in {@link #synchronizedMultimap}. 779 * 780 * <p>The returned multimap will be serializable if the specified multimap is serializable. 781 * 782 * @param multimap the multimap to be wrapped 783 * @return a synchronized view of the specified multimap 784 */ 785 public static <K, V> SetMultimap<K, V> synchronizedSetMultimap(SetMultimap<K, V> multimap) { 786 return Synchronized.setMultimap(multimap, null); 787 } 788 789 /** 790 * Returns an unmodifiable view of the specified {@code SetMultimap}. Query operations on the 791 * returned multimap "read through" to the specified multimap, and attempts to modify the returned 792 * multimap, either directly or through the multimap's views, result in an {@code 793 * UnsupportedOperationException}. 794 * 795 * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link 796 * Multimap#replaceValues} methods return collections that are modifiable. 797 * 798 * <p>The returned multimap will be serializable if the specified multimap is serializable. 799 * 800 * @param delegate the multimap for which an unmodifiable view is to be returned 801 * @return an unmodifiable view of the specified multimap 802 */ 803 public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap(SetMultimap<K, V> delegate) { 804 if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { 805 return delegate; 806 } 807 return new UnmodifiableSetMultimap<>(delegate); 808 } 809 810 /** 811 * Simply returns its argument. 812 * 813 * @deprecated no need to use this 814 * @since 10.0 815 */ 816 @Deprecated 817 public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( 818 ImmutableSetMultimap<K, V> delegate) { 819 return checkNotNull(delegate); 820 } 821 822 /** 823 * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the specified 824 * multimap. 825 * 826 * <p>You must follow the warnings described in {@link #synchronizedMultimap}. 827 * 828 * <p>The returned multimap will be serializable if the specified multimap is serializable. 829 * 830 * @param multimap the multimap to be wrapped 831 * @return a synchronized view of the specified multimap 832 */ 833 public static <K, V> SortedSetMultimap<K, V> synchronizedSortedSetMultimap( 834 SortedSetMultimap<K, V> multimap) { 835 return Synchronized.sortedSetMultimap(multimap, null); 836 } 837 838 /** 839 * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. Query operations on 840 * the returned multimap "read through" to the specified multimap, and attempts to modify the 841 * returned multimap, either directly or through the multimap's views, result in an {@code 842 * UnsupportedOperationException}. 843 * 844 * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link 845 * Multimap#replaceValues} methods return collections that are modifiable. 846 * 847 * <p>The returned multimap will be serializable if the specified multimap is serializable. 848 * 849 * @param delegate the multimap for which an unmodifiable view is to be returned 850 * @return an unmodifiable view of the specified multimap 851 */ 852 public static <K, V> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap( 853 SortedSetMultimap<K, V> delegate) { 854 if (delegate instanceof UnmodifiableSortedSetMultimap) { 855 return delegate; 856 } 857 return new UnmodifiableSortedSetMultimap<>(delegate); 858 } 859 860 /** 861 * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the specified multimap. 862 * 863 * <p>You must follow the warnings described in {@link #synchronizedMultimap}. 864 * 865 * @param multimap the multimap to be wrapped 866 * @return a synchronized view of the specified multimap 867 */ 868 public static <K, V> ListMultimap<K, V> synchronizedListMultimap(ListMultimap<K, V> multimap) { 869 return Synchronized.listMultimap(multimap, null); 870 } 871 872 /** 873 * Returns an unmodifiable view of the specified {@code ListMultimap}. Query operations on the 874 * returned multimap "read through" to the specified multimap, and attempts to modify the returned 875 * multimap, either directly or through the multimap's views, result in an {@code 876 * UnsupportedOperationException}. 877 * 878 * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link 879 * Multimap#replaceValues} methods return collections that are modifiable. 880 * 881 * <p>The returned multimap will be serializable if the specified multimap is serializable. 882 * 883 * @param delegate the multimap for which an unmodifiable view is to be returned 884 * @return an unmodifiable view of the specified multimap 885 */ 886 public static <K, V> ListMultimap<K, V> unmodifiableListMultimap(ListMultimap<K, V> delegate) { 887 if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { 888 return delegate; 889 } 890 return new UnmodifiableListMultimap<>(delegate); 891 } 892 893 /** 894 * Simply returns its argument. 895 * 896 * @deprecated no need to use this 897 * @since 10.0 898 */ 899 @Deprecated 900 public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( 901 ImmutableListMultimap<K, V> delegate) { 902 return checkNotNull(delegate); 903 } 904 905 /** 906 * Returns an unmodifiable view of the specified collection, preserving the interface for 907 * instances of {@code SortedSet}, {@code Set}, {@code List} and {@code Collection}, in that order 908 * of preference. 909 * 910 * @param collection the collection for which to return an unmodifiable view 911 * @return an unmodifiable view of the collection 912 */ 913 private static <V> Collection<V> unmodifiableValueCollection(Collection<V> collection) { 914 if (collection instanceof SortedSet) { 915 return Collections.unmodifiableSortedSet((SortedSet<V>) collection); 916 } else if (collection instanceof Set) { 917 return Collections.unmodifiableSet((Set<V>) collection); 918 } else if (collection instanceof List) { 919 return Collections.unmodifiableList((List<V>) collection); 920 } 921 return Collections.unmodifiableCollection(collection); 922 } 923 924 /** 925 * Returns an unmodifiable view of the specified collection of entries. The {@link Entry#setValue} 926 * operation throws an {@link UnsupportedOperationException}. If the specified collection is a 927 * {@code Set}, the returned collection is also a {@code Set}. 928 * 929 * @param entries the entries for which to return an unmodifiable view 930 * @return an unmodifiable view of the entries 931 */ 932 private static <K, V> Collection<Entry<K, V>> unmodifiableEntries( 933 Collection<Entry<K, V>> entries) { 934 if (entries instanceof Set) { 935 return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries); 936 } 937 return new Maps.UnmodifiableEntries<>(Collections.unmodifiableCollection(entries)); 938 } 939 940 /** 941 * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K, 942 * Collection<V>>} to {@code Map<K, List<V>>}. 943 * 944 * @since 15.0 945 */ 946 @Beta 947 @SuppressWarnings("unchecked") 948 // safe by specification of ListMultimap.asMap() 949 public static <K, V> Map<K, List<V>> asMap(ListMultimap<K, V> multimap) { 950 return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap(); 951 } 952 953 /** 954 * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K, 955 * Collection<V>>} to {@code Map<K, Set<V>>}. 956 * 957 * @since 15.0 958 */ 959 @Beta 960 @SuppressWarnings("unchecked") 961 // safe by specification of SetMultimap.asMap() 962 public static <K, V> Map<K, Set<V>> asMap(SetMultimap<K, V> multimap) { 963 return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap(); 964 } 965 966 /** 967 * Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type corrected from {@code 968 * Map<K, Collection<V>>} to {@code Map<K, SortedSet<V>>}. 969 * 970 * @since 15.0 971 */ 972 @Beta 973 @SuppressWarnings("unchecked") 974 // safe by specification of SortedSetMultimap.asMap() 975 public static <K, V> Map<K, SortedSet<V>> asMap(SortedSetMultimap<K, V> multimap) { 976 return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap(); 977 } 978 979 /** 980 * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity with the other 981 * more strongly-typed {@code asMap()} implementations. 982 * 983 * @since 15.0 984 */ 985 @Beta 986 public static <K, V> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) { 987 return multimap.asMap(); 988 } 989 990 /** 991 * Returns a multimap view of the specified map. The multimap is backed by the map, so changes to 992 * the map are reflected in the multimap, and vice versa. If the map is modified while an 993 * iteration over one of the multimap's collection views is in progress (except through the 994 * iterator's own {@code remove} operation, or through the {@code setValue} operation on a map 995 * entry returned by the iterator), the results of the iteration are undefined. 996 * 997 * <p>The multimap supports mapping removal, which removes the corresponding mapping from the map. 998 * It does not support any operations which might add mappings, such as {@code put}, {@code 999 * putAll} or {@code replaceValues}. 1000 * 1001 * <p>The returned multimap will be serializable if the specified map is serializable. 1002 * 1003 * @param map the backing map for the returned multimap view 1004 */ 1005 public static <K, V> SetMultimap<K, V> forMap(Map<K, V> map) { 1006 return new MapMultimap<>(map); 1007 } 1008 1009 /** @see Multimaps#forMap */ 1010 private static class MapMultimap<K, V> extends AbstractMultimap<K, V> 1011 implements SetMultimap<K, V>, Serializable { 1012 final Map<K, V> map; 1013 1014 MapMultimap(Map<K, V> map) { 1015 this.map = checkNotNull(map); 1016 } 1017 1018 @Override 1019 public int size() { 1020 return map.size(); 1021 } 1022 1023 @Override 1024 public boolean containsKey(Object key) { 1025 return map.containsKey(key); 1026 } 1027 1028 @Override 1029 public boolean containsValue(Object value) { 1030 return map.containsValue(value); 1031 } 1032 1033 @Override 1034 public boolean containsEntry(Object key, Object value) { 1035 return map.entrySet().contains(Maps.immutableEntry(key, value)); 1036 } 1037 1038 @Override 1039 public Set<V> get(final K key) { 1040 return new Sets.ImprovedAbstractSet<V>() { 1041 @Override 1042 public Iterator<V> iterator() { 1043 return new Iterator<V>() { 1044 int i; 1045 1046 @Override 1047 public boolean hasNext() { 1048 return (i == 0) && map.containsKey(key); 1049 } 1050 1051 @Override 1052 public V next() { 1053 if (!hasNext()) { 1054 throw new NoSuchElementException(); 1055 } 1056 i++; 1057 return map.get(key); 1058 } 1059 1060 @Override 1061 public void remove() { 1062 checkRemove(i == 1); 1063 i = -1; 1064 map.remove(key); 1065 } 1066 }; 1067 } 1068 1069 @Override 1070 public int size() { 1071 return map.containsKey(key) ? 1 : 0; 1072 } 1073 }; 1074 } 1075 1076 @Override 1077 public boolean put(K key, V value) { 1078 throw new UnsupportedOperationException(); 1079 } 1080 1081 @Override 1082 public boolean putAll(K key, Iterable<? extends V> values) { 1083 throw new UnsupportedOperationException(); 1084 } 1085 1086 @Override 1087 public boolean putAll(Multimap<? extends K, ? extends V> multimap) { 1088 throw new UnsupportedOperationException(); 1089 } 1090 1091 @Override 1092 public Set<V> replaceValues(K key, Iterable<? extends V> values) { 1093 throw new UnsupportedOperationException(); 1094 } 1095 1096 @Override 1097 public boolean remove(Object key, Object value) { 1098 return map.entrySet().remove(Maps.immutableEntry(key, value)); 1099 } 1100 1101 @Override 1102 public Set<V> removeAll(Object key) { 1103 Set<V> values = new HashSet<V>(2); 1104 if (!map.containsKey(key)) { 1105 return values; 1106 } 1107 values.add(map.remove(key)); 1108 return values; 1109 } 1110 1111 @Override 1112 public void clear() { 1113 map.clear(); 1114 } 1115 1116 @Override 1117 Set<K> createKeySet() { 1118 return map.keySet(); 1119 } 1120 1121 @Override 1122 Collection<V> createValues() { 1123 return map.values(); 1124 } 1125 1126 @Override 1127 public Set<Entry<K, V>> entries() { 1128 return map.entrySet(); 1129 } 1130 1131 @Override 1132 Collection<Entry<K, V>> createEntries() { 1133 throw new AssertionError("unreachable"); 1134 } 1135 1136 @Override 1137 Multiset<K> createKeys() { 1138 return new Multimaps.Keys<K, V>(this); 1139 } 1140 1141 @Override 1142 Iterator<Entry<K, V>> entryIterator() { 1143 return map.entrySet().iterator(); 1144 } 1145 1146 @Override 1147 Map<K, Collection<V>> createAsMap() { 1148 return new AsMap<>(this); 1149 } 1150 1151 @Override 1152 public int hashCode() { 1153 return map.hashCode(); 1154 } 1155 1156 private static final long serialVersionUID = 7845222491160860175L; 1157 } 1158 1159 /** 1160 * Returns a view of a multimap where each value is transformed by a function. All other 1161 * properties of the multimap, such as iteration order, are left intact. For example, the code: 1162 * 1163 * <pre>{@code 1164 * Multimap<String, Integer> multimap = 1165 * ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6); 1166 * Function<Integer, String> square = new Function<Integer, String>() { 1167 * public String apply(Integer in) { 1168 * return Integer.toString(in * in); 1169 * } 1170 * }; 1171 * Multimap<String, String> transformed = 1172 * Multimaps.transformValues(multimap, square); 1173 * System.out.println(transformed); 1174 * }</pre> 1175 * 1176 * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}. 1177 * 1178 * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view 1179 * supports removal operations, and these are reflected in the underlying multimap. 1180 * 1181 * <p>It's acceptable for the underlying multimap to contain null keys, and even null values 1182 * provided that the function is capable of accepting null input. The transformed multimap might 1183 * contain null values, if the function sometimes gives a null result. 1184 * 1185 * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap 1186 * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless, 1187 * since there is not a definition of {@code equals} or {@code hashCode} for general collections, 1188 * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a 1189 * {@code Set}. 1190 * 1191 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned 1192 * multimap to be a view, but it means that the function will be applied many times for bulk 1193 * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to 1194 * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned 1195 * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your 1196 * choosing. 1197 * 1198 * @since 7.0 1199 */ 1200 public static <K, V1, V2> Multimap<K, V2> transformValues( 1201 Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { 1202 checkNotNull(function); 1203 EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); 1204 return transformEntries(fromMultimap, transformer); 1205 } 1206 1207 /** 1208 * Returns a view of a multimap whose values are derived from the original multimap's entries. In 1209 * contrast to {@link #transformValues}, this method's entry-transformation logic may depend on 1210 * the key as well as the value. 1211 * 1212 * <p>All other properties of the transformed multimap, such as iteration order, are left intact. 1213 * For example, the code: 1214 * 1215 * <pre>{@code 1216 * SetMultimap<String, Integer> multimap = 1217 * ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6); 1218 * EntryTransformer<String, Integer, String> transformer = 1219 * new EntryTransformer<String, Integer, String>() { 1220 * public String transformEntry(String key, Integer value) { 1221 * return (value >= 0) ? key : "no" + key; 1222 * } 1223 * }; 1224 * Multimap<String, String> transformed = 1225 * Multimaps.transformEntries(multimap, transformer); 1226 * System.out.println(transformed); 1227 * }</pre> 1228 * 1229 * ... prints {@code {a=[a, a], b=[nob]}}. 1230 * 1231 * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view 1232 * supports removal operations, and these are reflected in the underlying multimap. 1233 * 1234 * <p>It's acceptable for the underlying multimap to contain null keys and null values provided 1235 * that the transformer is capable of accepting null inputs. The transformed multimap might 1236 * contain null values if the transformer sometimes gives a null result. 1237 * 1238 * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap 1239 * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless, 1240 * since there is not a definition of {@code equals} or {@code hashCode} for general collections, 1241 * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a 1242 * {@code Set}. 1243 * 1244 * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned 1245 * multimap to be a view, but it means that the transformer will be applied many times for bulk 1246 * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform 1247 * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap 1248 * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing. 1249 * 1250 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code 1251 * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of 1252 * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as 1253 * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the 1254 * transformed multimap. 1255 * 1256 * @since 7.0 1257 */ 1258 public static <K, V1, V2> Multimap<K, V2> transformEntries( 1259 Multimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 1260 return new TransformedEntriesMultimap<>(fromMap, transformer); 1261 } 1262 1263 private static class TransformedEntriesMultimap<K, V1, V2> extends AbstractMultimap<K, V2> { 1264 final Multimap<K, V1> fromMultimap; 1265 final EntryTransformer<? super K, ? super V1, V2> transformer; 1266 1267 TransformedEntriesMultimap( 1268 Multimap<K, V1> fromMultimap, 1269 final EntryTransformer<? super K, ? super V1, V2> transformer) { 1270 this.fromMultimap = checkNotNull(fromMultimap); 1271 this.transformer = checkNotNull(transformer); 1272 } 1273 1274 Collection<V2> transform(K key, Collection<V1> values) { 1275 Function<? super V1, V2> function = Maps.asValueToValueFunction(transformer, key); 1276 if (values instanceof List) { 1277 return Lists.transform((List<V1>) values, function); 1278 } else { 1279 return Collections2.transform(values, function); 1280 } 1281 } 1282 1283 @Override 1284 Map<K, Collection<V2>> createAsMap() { 1285 return Maps.transformEntries( 1286 fromMultimap.asMap(), 1287 new EntryTransformer<K, Collection<V1>, Collection<V2>>() { 1288 @Override 1289 public Collection<V2> transformEntry(K key, Collection<V1> value) { 1290 return transform(key, value); 1291 } 1292 }); 1293 } 1294 1295 @Override 1296 public void clear() { 1297 fromMultimap.clear(); 1298 } 1299 1300 @Override 1301 public boolean containsKey(Object key) { 1302 return fromMultimap.containsKey(key); 1303 } 1304 1305 @Override 1306 Collection<Entry<K, V2>> createEntries() { 1307 return new Entries(); 1308 } 1309 1310 @Override 1311 Iterator<Entry<K, V2>> entryIterator() { 1312 return Iterators.transform( 1313 fromMultimap.entries().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); 1314 } 1315 1316 @Override 1317 public Collection<V2> get(final K key) { 1318 return transform(key, fromMultimap.get(key)); 1319 } 1320 1321 @Override 1322 public boolean isEmpty() { 1323 return fromMultimap.isEmpty(); 1324 } 1325 1326 @Override 1327 Set<K> createKeySet() { 1328 return fromMultimap.keySet(); 1329 } 1330 1331 @Override 1332 Multiset<K> createKeys() { 1333 return fromMultimap.keys(); 1334 } 1335 1336 @Override 1337 public boolean put(K key, V2 value) { 1338 throw new UnsupportedOperationException(); 1339 } 1340 1341 @Override 1342 public boolean putAll(K key, Iterable<? extends V2> values) { 1343 throw new UnsupportedOperationException(); 1344 } 1345 1346 @Override 1347 public boolean putAll(Multimap<? extends K, ? extends V2> multimap) { 1348 throw new UnsupportedOperationException(); 1349 } 1350 1351 @SuppressWarnings("unchecked") 1352 @Override 1353 public boolean remove(Object key, Object value) { 1354 return get((K) key).remove(value); 1355 } 1356 1357 @SuppressWarnings("unchecked") 1358 @Override 1359 public Collection<V2> removeAll(Object key) { 1360 return transform((K) key, fromMultimap.removeAll(key)); 1361 } 1362 1363 @Override 1364 public Collection<V2> replaceValues(K key, Iterable<? extends V2> values) { 1365 throw new UnsupportedOperationException(); 1366 } 1367 1368 @Override 1369 public int size() { 1370 return fromMultimap.size(); 1371 } 1372 1373 @Override 1374 Collection<V2> createValues() { 1375 return Collections2.transform( 1376 fromMultimap.entries(), Maps.<K, V1, V2>asEntryToValueFunction(transformer)); 1377 } 1378 } 1379 1380 /** 1381 * Returns a view of a {@code ListMultimap} where each value is transformed by a function. All 1382 * other properties of the multimap, such as iteration order, are left intact. For example, the 1383 * code: 1384 * 1385 * <pre>{@code 1386 * ListMultimap<String, Integer> multimap 1387 * = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9); 1388 * Function<Integer, Double> sqrt = 1389 * new Function<Integer, Double>() { 1390 * public Double apply(Integer in) { 1391 * return Math.sqrt((int) in); 1392 * } 1393 * }; 1394 * ListMultimap<String, Double> transformed = Multimaps.transformValues(map, 1395 * sqrt); 1396 * System.out.println(transformed); 1397 * }</pre> 1398 * 1399 * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. 1400 * 1401 * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view 1402 * supports removal operations, and these are reflected in the underlying multimap. 1403 * 1404 * <p>It's acceptable for the underlying multimap to contain null keys, and even null values 1405 * provided that the function is capable of accepting null input. The transformed multimap might 1406 * contain null values, if the function sometimes gives a null result. 1407 * 1408 * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap 1409 * is. 1410 * 1411 * <p>The function is applied lazily, invoked when needed. This is necessary for the returned 1412 * multimap to be a view, but it means that the function will be applied many times for bulk 1413 * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to 1414 * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned 1415 * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your 1416 * choosing. 1417 * 1418 * @since 7.0 1419 */ 1420 public static <K, V1, V2> ListMultimap<K, V2> transformValues( 1421 ListMultimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { 1422 checkNotNull(function); 1423 EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); 1424 return transformEntries(fromMultimap, transformer); 1425 } 1426 1427 /** 1428 * Returns a view of a {@code ListMultimap} whose values are derived from the original multimap's 1429 * entries. In contrast to {@link #transformValues(ListMultimap, Function)}, this method's 1430 * entry-transformation logic may depend on the key as well as the value. 1431 * 1432 * <p>All other properties of the transformed multimap, such as iteration order, are left intact. 1433 * For example, the code: 1434 * 1435 * <pre>{@code 1436 * Multimap<String, Integer> multimap = 1437 * ImmutableMultimap.of("a", 1, "a", 4, "b", 6); 1438 * EntryTransformer<String, Integer, String> transformer = 1439 * new EntryTransformer<String, Integer, String>() { 1440 * public String transformEntry(String key, Integer value) { 1441 * return key + value; 1442 * } 1443 * }; 1444 * Multimap<String, String> transformed = 1445 * Multimaps.transformEntries(multimap, transformer); 1446 * System.out.println(transformed); 1447 * }</pre> 1448 * 1449 * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. 1450 * 1451 * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view 1452 * supports removal operations, and these are reflected in the underlying multimap. 1453 * 1454 * <p>It's acceptable for the underlying multimap to contain null keys and null values provided 1455 * that the transformer is capable of accepting null inputs. The transformed multimap might 1456 * contain null values if the transformer sometimes gives a null result. 1457 * 1458 * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap 1459 * is. 1460 * 1461 * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned 1462 * multimap to be a view, but it means that the transformer will be applied many times for bulk 1463 * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform 1464 * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap 1465 * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing. 1466 * 1467 * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code 1468 * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of 1469 * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as 1470 * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the 1471 * transformed multimap. 1472 * 1473 * @since 7.0 1474 */ 1475 public static <K, V1, V2> ListMultimap<K, V2> transformEntries( 1476 ListMultimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { 1477 return new TransformedEntriesListMultimap<>(fromMap, transformer); 1478 } 1479 1480 private static final class TransformedEntriesListMultimap<K, V1, V2> 1481 extends TransformedEntriesMultimap<K, V1, V2> implements ListMultimap<K, V2> { 1482 1483 TransformedEntriesListMultimap( 1484 ListMultimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) { 1485 super(fromMultimap, transformer); 1486 } 1487 1488 @Override 1489 List<V2> transform(K key, Collection<V1> values) { 1490 return Lists.transform((List<V1>) values, Maps.asValueToValueFunction(transformer, key)); 1491 } 1492 1493 @Override 1494 public List<V2> get(K key) { 1495 return transform(key, fromMultimap.get(key)); 1496 } 1497 1498 @SuppressWarnings("unchecked") 1499 @Override 1500 public List<V2> removeAll(Object key) { 1501 return transform((K) key, fromMultimap.removeAll(key)); 1502 } 1503 1504 @Override 1505 public List<V2> replaceValues(K key, Iterable<? extends V2> values) { 1506 throw new UnsupportedOperationException(); 1507 } 1508 } 1509 1510 /** 1511 * Creates an index {@code ImmutableListMultimap} that contains the results of applying a 1512 * specified function to each item in an {@code Iterable} of values. Each value will be stored as 1513 * a value in the resulting multimap, yielding a multimap with the same size as the input 1514 * iterable. The key used to store that value in the multimap will be the result of calling the 1515 * function on that value. The resulting multimap is created as an immutable snapshot. In the 1516 * returned multimap, keys appear in the order they are first encountered, and the values 1517 * corresponding to each key appear in the same order as they are encountered. 1518 * 1519 * <p>For example, 1520 * 1521 * <pre>{@code 1522 * List<String> badGuys = 1523 * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); 1524 * Function<String, Integer> stringLengthFunction = ...; 1525 * Multimap<Integer, String> index = 1526 * Multimaps.index(badGuys, stringLengthFunction); 1527 * System.out.println(index); 1528 * }</pre> 1529 * 1530 * <p>prints 1531 * 1532 * <pre>{@code 1533 * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]} 1534 * }</pre> 1535 * 1536 * <p>The returned multimap is serializable if its keys and values are all serializable. 1537 * 1538 * @param values the values to use when constructing the {@code ImmutableListMultimap} 1539 * @param keyFunction the function used to produce the key for each value 1540 * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code 1541 * keyFunction} on each value in the input collection to that value 1542 * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code 1543 * keyFunction} produces {@code null} for any key 1544 */ 1545 public static <K, V> ImmutableListMultimap<K, V> index( 1546 Iterable<V> values, Function<? super V, K> keyFunction) { 1547 return index(values.iterator(), keyFunction); 1548 } 1549 1550 /** 1551 * Creates an index {@code ImmutableListMultimap} that contains the results of applying a 1552 * specified function to each item in an {@code Iterator} of values. Each value will be stored as 1553 * a value in the resulting multimap, yielding a multimap with the same size as the input 1554 * iterator. The key used to store that value in the multimap will be the result of calling the 1555 * function on that value. The resulting multimap is created as an immutable snapshot. In the 1556 * returned multimap, keys appear in the order they are first encountered, and the values 1557 * corresponding to each key appear in the same order as they are encountered. 1558 * 1559 * <p>For example, 1560 * 1561 * <pre>{@code 1562 * List<String> badGuys = 1563 * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); 1564 * Function<String, Integer> stringLengthFunction = ...; 1565 * Multimap<Integer, String> index = 1566 * Multimaps.index(badGuys.iterator(), stringLengthFunction); 1567 * System.out.println(index); 1568 * }</pre> 1569 * 1570 * <p>prints 1571 * 1572 * <pre>{@code 1573 * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]} 1574 * }</pre> 1575 * 1576 * <p>The returned multimap is serializable if its keys and values are all serializable. 1577 * 1578 * @param values the values to use when constructing the {@code ImmutableListMultimap} 1579 * @param keyFunction the function used to produce the key for each value 1580 * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code 1581 * keyFunction} on each value in the input collection to that value 1582 * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code 1583 * keyFunction} produces {@code null} for any key 1584 * @since 10.0 1585 */ 1586 public static <K, V> ImmutableListMultimap<K, V> index( 1587 Iterator<V> values, Function<? super V, K> keyFunction) { 1588 checkNotNull(keyFunction); 1589 ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); 1590 while (values.hasNext()) { 1591 V value = values.next(); 1592 checkNotNull(value, values); 1593 builder.put(keyFunction.apply(value), value); 1594 } 1595 return builder.build(); 1596 } 1597 1598 static class Keys<K, V> extends AbstractMultiset<K> { 1599 @Weak final Multimap<K, V> multimap; 1600 1601 Keys(Multimap<K, V> multimap) { 1602 this.multimap = multimap; 1603 } 1604 1605 @Override 1606 Iterator<Multiset.Entry<K>> entryIterator() { 1607 return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>( 1608 multimap.asMap().entrySet().iterator()) { 1609 @Override 1610 Multiset.Entry<K> transform(final Map.Entry<K, Collection<V>> backingEntry) { 1611 return new Multisets.AbstractEntry<K>() { 1612 @Override 1613 public K getElement() { 1614 return backingEntry.getKey(); 1615 } 1616 1617 @Override 1618 public int getCount() { 1619 return backingEntry.getValue().size(); 1620 } 1621 }; 1622 } 1623 }; 1624 } 1625 1626 @Override 1627 public Spliterator<K> spliterator() { 1628 return CollectSpliterators.map(multimap.entries().spliterator(), Map.Entry::getKey); 1629 } 1630 1631 @Override 1632 public void forEach(Consumer<? super K> consumer) { 1633 checkNotNull(consumer); 1634 multimap.entries().forEach(entry -> consumer.accept(entry.getKey())); 1635 } 1636 1637 @Override 1638 int distinctElements() { 1639 return multimap.asMap().size(); 1640 } 1641 1642 @Override 1643 Set<Multiset.Entry<K>> createEntrySet() { 1644 return new KeysEntrySet(); 1645 } 1646 1647 @WeakOuter 1648 class KeysEntrySet extends Multisets.EntrySet<K> { 1649 @Override 1650 Multiset<K> multiset() { 1651 return Keys.this; 1652 } 1653 1654 @Override 1655 public Iterator<Multiset.Entry<K>> iterator() { 1656 return entryIterator(); 1657 } 1658 1659 @Override 1660 public int size() { 1661 return distinctElements(); 1662 } 1663 1664 @Override 1665 public boolean isEmpty() { 1666 return multimap.isEmpty(); 1667 } 1668 1669 @Override 1670 public boolean contains(@NullableDecl Object o) { 1671 if (o instanceof Multiset.Entry) { 1672 Multiset.Entry<?> entry = (Multiset.Entry<?>) o; 1673 Collection<V> collection = multimap.asMap().get(entry.getElement()); 1674 return collection != null && collection.size() == entry.getCount(); 1675 } 1676 return false; 1677 } 1678 1679 @Override 1680 public boolean remove(@NullableDecl Object o) { 1681 if (o instanceof Multiset.Entry) { 1682 Multiset.Entry<?> entry = (Multiset.Entry<?>) o; 1683 Collection<V> collection = multimap.asMap().get(entry.getElement()); 1684 if (collection != null && collection.size() == entry.getCount()) { 1685 collection.clear(); 1686 return true; 1687 } 1688 } 1689 return false; 1690 } 1691 } 1692 1693 @Override 1694 public boolean contains(@NullableDecl Object element) { 1695 return multimap.containsKey(element); 1696 } 1697 1698 @Override 1699 public Iterator<K> iterator() { 1700 return Maps.keyIterator(multimap.entries().iterator()); 1701 } 1702 1703 @Override 1704 public int count(@NullableDecl Object element) { 1705 Collection<V> values = Maps.safeGet(multimap.asMap(), element); 1706 return (values == null) ? 0 : values.size(); 1707 } 1708 1709 @Override 1710 public int remove(@NullableDecl Object element, int occurrences) { 1711 checkNonnegative(occurrences, "occurrences"); 1712 if (occurrences == 0) { 1713 return count(element); 1714 } 1715 1716 Collection<V> values = Maps.safeGet(multimap.asMap(), element); 1717 1718 if (values == null) { 1719 return 0; 1720 } 1721 1722 int oldCount = values.size(); 1723 if (occurrences >= oldCount) { 1724 values.clear(); 1725 } else { 1726 Iterator<V> iterator = values.iterator(); 1727 for (int i = 0; i < occurrences; i++) { 1728 iterator.next(); 1729 iterator.remove(); 1730 } 1731 } 1732 return oldCount; 1733 } 1734 1735 @Override 1736 public void clear() { 1737 multimap.clear(); 1738 } 1739 1740 @Override 1741 public Set<K> elementSet() { 1742 return multimap.keySet(); 1743 } 1744 } 1745 1746 /** A skeleton implementation of {@link Multimap#entries()}. */ 1747 abstract static class Entries<K, V> extends AbstractCollection<Map.Entry<K, V>> { 1748 abstract Multimap<K, V> multimap(); 1749 1750 @Override 1751 public int size() { 1752 return multimap().size(); 1753 } 1754 1755 @Override 1756 public boolean contains(@NullableDecl Object o) { 1757 if (o instanceof Map.Entry) { 1758 Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; 1759 return multimap().containsEntry(entry.getKey(), entry.getValue()); 1760 } 1761 return false; 1762 } 1763 1764 @Override 1765 public boolean remove(@NullableDecl Object o) { 1766 if (o instanceof Map.Entry) { 1767 Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; 1768 return multimap().remove(entry.getKey(), entry.getValue()); 1769 } 1770 return false; 1771 } 1772 1773 @Override 1774 public void clear() { 1775 multimap().clear(); 1776 } 1777 } 1778 1779 /** A skeleton implementation of {@link Multimap#asMap()}. */ 1780 static final class AsMap<K, V> extends Maps.ViewCachingAbstractMap<K, Collection<V>> { 1781 @Weak private final Multimap<K, V> multimap; 1782 1783 AsMap(Multimap<K, V> multimap) { 1784 this.multimap = checkNotNull(multimap); 1785 } 1786 1787 @Override 1788 public int size() { 1789 return multimap.keySet().size(); 1790 } 1791 1792 @Override 1793 protected Set<Entry<K, Collection<V>>> createEntrySet() { 1794 return new EntrySet(); 1795 } 1796 1797 void removeValuesForKey(Object key) { 1798 multimap.keySet().remove(key); 1799 } 1800 1801 @WeakOuter 1802 class EntrySet extends Maps.EntrySet<K, Collection<V>> { 1803 @Override 1804 Map<K, Collection<V>> map() { 1805 return AsMap.this; 1806 } 1807 1808 @Override 1809 public Iterator<Entry<K, Collection<V>>> iterator() { 1810 return Maps.asMapEntryIterator( 1811 multimap.keySet(), 1812 new Function<K, Collection<V>>() { 1813 @Override 1814 public Collection<V> apply(K key) { 1815 return multimap.get(key); 1816 } 1817 }); 1818 } 1819 1820 @Override 1821 public boolean remove(Object o) { 1822 if (!contains(o)) { 1823 return false; 1824 } 1825 Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; 1826 removeValuesForKey(entry.getKey()); 1827 return true; 1828 } 1829 } 1830 1831 @SuppressWarnings("unchecked") 1832 @Override 1833 public Collection<V> get(Object key) { 1834 return containsKey(key) ? multimap.get((K) key) : null; 1835 } 1836 1837 @Override 1838 public Collection<V> remove(Object key) { 1839 return containsKey(key) ? multimap.removeAll(key) : null; 1840 } 1841 1842 @Override 1843 public Set<K> keySet() { 1844 return multimap.keySet(); 1845 } 1846 1847 @Override 1848 public boolean isEmpty() { 1849 return multimap.isEmpty(); 1850 } 1851 1852 @Override 1853 public boolean containsKey(Object key) { 1854 return multimap.containsKey(key); 1855 } 1856 1857 @Override 1858 public void clear() { 1859 multimap.clear(); 1860 } 1861 } 1862 1863 /** 1864 * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a 1865 * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect 1866 * the other. 1867 * 1868 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 1869 * other methods are supported by the multimap and its views. When adding a key that doesn't 1870 * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code 1871 * replaceValues()} methods throw an {@link IllegalArgumentException}. 1872 * 1873 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 1874 * multimap or its views, only mappings whose keys satisfy the filter will be removed from the 1875 * underlying multimap. 1876 * 1877 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 1878 * 1879 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 1880 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 1881 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 1882 * copy. 1883 * 1884 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 1885 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1886 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 1887 * 1888 * @since 11.0 1889 */ 1890 public static <K, V> Multimap<K, V> filterKeys( 1891 Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 1892 if (unfiltered instanceof SetMultimap) { 1893 return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate); 1894 } else if (unfiltered instanceof ListMultimap) { 1895 return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate); 1896 } else if (unfiltered instanceof FilteredKeyMultimap) { 1897 FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered; 1898 return new FilteredKeyMultimap<>( 1899 prev.unfiltered, Predicates.<K>and(prev.keyPredicate, keyPredicate)); 1900 } else if (unfiltered instanceof FilteredMultimap) { 1901 FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered; 1902 return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); 1903 } else { 1904 return new FilteredKeyMultimap<>(unfiltered, keyPredicate); 1905 } 1906 } 1907 1908 /** 1909 * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a 1910 * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect 1911 * the other. 1912 * 1913 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 1914 * other methods are supported by the multimap and its views. When adding a key that doesn't 1915 * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code 1916 * replaceValues()} methods throw an {@link IllegalArgumentException}. 1917 * 1918 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 1919 * multimap or its views, only mappings whose keys satisfy the filter will be removed from the 1920 * underlying multimap. 1921 * 1922 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 1923 * 1924 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 1925 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 1926 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 1927 * copy. 1928 * 1929 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 1930 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1931 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 1932 * 1933 * @since 14.0 1934 */ 1935 public static <K, V> SetMultimap<K, V> filterKeys( 1936 SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 1937 if (unfiltered instanceof FilteredKeySetMultimap) { 1938 FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered; 1939 return new FilteredKeySetMultimap<>( 1940 prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate)); 1941 } else if (unfiltered instanceof FilteredSetMultimap) { 1942 FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered; 1943 return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); 1944 } else { 1945 return new FilteredKeySetMultimap<>(unfiltered, keyPredicate); 1946 } 1947 } 1948 1949 /** 1950 * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a 1951 * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect 1952 * the other. 1953 * 1954 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 1955 * other methods are supported by the multimap and its views. When adding a key that doesn't 1956 * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code 1957 * replaceValues()} methods throw an {@link IllegalArgumentException}. 1958 * 1959 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 1960 * multimap or its views, only mappings whose keys satisfy the filter will be removed from the 1961 * underlying multimap. 1962 * 1963 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 1964 * 1965 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 1966 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 1967 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 1968 * copy. 1969 * 1970 * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at 1971 * {@link Predicate#apply}. Do not provide a predicate such as {@code 1972 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 1973 * 1974 * @since 14.0 1975 */ 1976 public static <K, V> ListMultimap<K, V> filterKeys( 1977 ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { 1978 if (unfiltered instanceof FilteredKeyListMultimap) { 1979 FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered; 1980 return new FilteredKeyListMultimap<>( 1981 prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate)); 1982 } else { 1983 return new FilteredKeyListMultimap<>(unfiltered, keyPredicate); 1984 } 1985 } 1986 1987 /** 1988 * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a 1989 * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect 1990 * the other. 1991 * 1992 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 1993 * other methods are supported by the multimap and its views. When adding a value that doesn't 1994 * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code 1995 * replaceValues()} methods throw an {@link IllegalArgumentException}. 1996 * 1997 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 1998 * multimap or its views, only mappings whose value satisfy the filter will be removed from the 1999 * underlying multimap. 2000 * 2001 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2002 * 2003 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 2004 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 2005 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 2006 * copy. 2007 * 2008 * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented 2009 * at {@link Predicate#apply}. Do not provide a predicate such as {@code 2010 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2011 * 2012 * @since 11.0 2013 */ 2014 public static <K, V> Multimap<K, V> filterValues( 2015 Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2016 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2017 } 2018 2019 /** 2020 * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a 2021 * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect 2022 * the other. 2023 * 2024 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 2025 * other methods are supported by the multimap and its views. When adding a value that doesn't 2026 * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code 2027 * replaceValues()} methods throw an {@link IllegalArgumentException}. 2028 * 2029 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2030 * multimap or its views, only mappings whose value satisfy the filter will be removed from the 2031 * underlying multimap. 2032 * 2033 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2034 * 2035 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 2036 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 2037 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 2038 * copy. 2039 * 2040 * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented 2041 * at {@link Predicate#apply}. Do not provide a predicate such as {@code 2042 * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. 2043 * 2044 * @since 14.0 2045 */ 2046 public static <K, V> SetMultimap<K, V> filterValues( 2047 SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { 2048 return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); 2049 } 2050 2051 /** 2052 * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The 2053 * returned multimap is a live view of {@code unfiltered}; changes to one affect the other. 2054 * 2055 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 2056 * other methods are supported by the multimap and its views. When adding a key/value pair that 2057 * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code 2058 * replaceValues()} methods throw an {@link IllegalArgumentException}. 2059 * 2060 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2061 * multimap or its views, only mappings whose keys satisfy the filter will be removed from the 2062 * underlying multimap. 2063 * 2064 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2065 * 2066 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 2067 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 2068 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 2069 * copy. 2070 * 2071 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented 2072 * at {@link Predicate#apply}. 2073 * 2074 * @since 11.0 2075 */ 2076 public static <K, V> Multimap<K, V> filterEntries( 2077 Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2078 checkNotNull(entryPredicate); 2079 if (unfiltered instanceof SetMultimap) { 2080 return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate); 2081 } 2082 return (unfiltered instanceof FilteredMultimap) 2083 ? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate) 2084 : new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); 2085 } 2086 2087 /** 2088 * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The 2089 * returned multimap is a live view of {@code unfiltered}; changes to one affect the other. 2090 * 2091 * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all 2092 * other methods are supported by the multimap and its views. When adding a key/value pair that 2093 * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code 2094 * replaceValues()} methods throw an {@link IllegalArgumentException}. 2095 * 2096 * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered 2097 * multimap or its views, only mappings whose keys satisfy the filter will be removed from the 2098 * underlying multimap. 2099 * 2100 * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. 2101 * 2102 * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every 2103 * key/value mapping in the underlying multimap and determine which satisfy the filter. When a 2104 * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the 2105 * copy. 2106 * 2107 * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented 2108 * at {@link Predicate#apply}. 2109 * 2110 * @since 14.0 2111 */ 2112 public static <K, V> SetMultimap<K, V> filterEntries( 2113 SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { 2114 checkNotNull(entryPredicate); 2115 return (unfiltered instanceof FilteredSetMultimap) 2116 ? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate) 2117 : new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); 2118 } 2119 2120 /** 2121 * Support removal operations when filtering a filtered multimap. Since a filtered multimap has 2122 * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would 2123 * lead to a multimap whose removal operations would fail. This method combines the predicates to 2124 * avoid that problem. 2125 */ 2126 private static <K, V> Multimap<K, V> filterFiltered( 2127 FilteredMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { 2128 Predicate<Entry<K, V>> predicate = 2129 Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate); 2130 return new FilteredEntryMultimap<>(multimap.unfiltered(), predicate); 2131 } 2132 2133 /** 2134 * Support removal operations when filtering a filtered multimap. Since a filtered multimap has 2135 * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would 2136 * lead to a multimap whose removal operations would fail. This method combines the predicates to 2137 * avoid that problem. 2138 */ 2139 private static <K, V> SetMultimap<K, V> filterFiltered( 2140 FilteredSetMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { 2141 Predicate<Entry<K, V>> predicate = 2142 Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate); 2143 return new FilteredEntrySetMultimap<>(multimap.unfiltered(), predicate); 2144 } 2145 2146 static boolean equalsImpl(Multimap<?, ?> multimap, @NullableDecl Object object) { 2147 if (object == multimap) { 2148 return true; 2149 } 2150 if (object instanceof Multimap) { 2151 Multimap<?, ?> that = (Multimap<?, ?>) object; 2152 return multimap.asMap().equals(that.asMap()); 2153 } 2154 return false; 2155 } 2156 2157 // TODO(jlevy): Create methods that filter a SortedSetMultimap. 2158}