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