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