001/* 002 * Copyright (C) 2009 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 java.lang.Math.max; 022import static java.util.Arrays.asList; 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.MoreObjects; 029import com.google.errorprone.annotations.CanIgnoreReturnValue; 030import com.google.errorprone.annotations.DoNotCall; 031import com.google.errorprone.annotations.concurrent.LazyInit; 032import com.google.j2objc.annotations.RetainedWith; 033import com.google.j2objc.annotations.Weak; 034import java.io.IOException; 035import java.io.InvalidObjectException; 036import java.io.ObjectInputStream; 037import java.io.ObjectOutputStream; 038import java.util.Collection; 039import java.util.Comparator; 040import java.util.Map; 041import java.util.Map.Entry; 042import java.util.Set; 043import java.util.function.Function; 044import java.util.stream.Collector; 045import java.util.stream.Stream; 046import org.jspecify.annotations.Nullable; 047 048/** 049 * A {@link SetMultimap} whose contents will never change, with many other important properties 050 * detailed at {@link ImmutableCollection}. 051 * 052 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i> 053 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior. 054 * Undefined behavior and bugs will result. 055 * 056 * <p>See the Guava User Guide article on <a href= 057 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>. 058 * 059 * @author Mike Ward 060 * @since 2.0 061 */ 062@GwtCompatible(serializable = true, emulated = true) 063public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V> 064 implements SetMultimap<K, V> { 065 /** 066 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap} 067 * whose keys and values are the result of applying the provided mapping functions to the input 068 * elements. 069 * 070 * <p>For streams with defined encounter order (as defined in the Ordering section of the {@link 071 * java.util.stream} Javadoc), that order is preserved, but entries are <a 072 * href="ImmutableMultimap.html#iteration">grouped by key</a>. 073 * 074 * <p>Example: 075 * 076 * {@snippet : 077 * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP = 078 * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") 079 * .collect(toImmutableSetMultimap(str -> str.charAt(0), str -> str.substring(1))); 080 * 081 * // is equivalent to 082 * 083 * static final Multimap<Character, String> FIRST_LETTER_MULTIMAP = 084 * new ImmutableSetMultimap.Builder<Character, String>() 085 * .put('b', "anana") 086 * .putAll('a', "pple", "sparagus") 087 * .putAll('c', "arrot", "herry") 088 * .build(); 089 * } 090 * 091 * @since 33.2.0 (available since 21.0 in guava-jre) 092 */ 093 @SuppressWarnings("Java7ApiChecker") 094 @IgnoreJRERequirement // Users will use this only if they're already using streams. 095 public static <T extends @Nullable Object, K, V> 096 Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap( 097 Function<? super T, ? extends K> keyFunction, 098 Function<? super T, ? extends V> valueFunction) { 099 return CollectCollectors.toImmutableSetMultimap(keyFunction, valueFunction); 100 } 101 102 /** 103 * Returns a {@code Collector} accumulating entries into an {@code ImmutableSetMultimap}. Each 104 * input element is mapped to a key and a stream of values, each of which are put into the 105 * resulting {@code Multimap}, in the encounter order of the stream and the encounter order of the 106 * streams of values. 107 * 108 * <p>Example: 109 * 110 * {@snippet : 111 * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP = 112 * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") 113 * .collect( 114 * flatteningToImmutableSetMultimap( 115 * str -> str.charAt(0), 116 * str -> str.substring(1).chars().mapToObj(c -> (char) c)); 117 * 118 * // is equivalent to 119 * 120 * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP = 121 * ImmutableSetMultimap.<Character, Character>builder() 122 * .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')) 123 * .putAll('a', Arrays.asList('p', 'p', 'l', 'e')) 124 * .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')) 125 * .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')) 126 * .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')) 127 * .build(); 128 * 129 * // after deduplication, the resulting multimap is equivalent to 130 * 131 * static final ImmutableSetMultimap<Character, Character> FIRST_LETTER_MULTIMAP = 132 * ImmutableSetMultimap.<Character, Character>builder() 133 * .putAll('b', Arrays.asList('a', 'n')) 134 * .putAll('a', Arrays.asList('p', 'l', 'e', 's', 'a', 'r', 'g', 'u')) 135 * .putAll('c', Arrays.asList('a', 'r', 'o', 't', 'h', 'e', 'y')) 136 * .build(); 137 * } 138 * 139 * } 140 * 141 * @since 33.2.0 (available since 21.0 in guava-jre) 142 */ 143 @SuppressWarnings("Java7ApiChecker") 144 @IgnoreJRERequirement // Users will use this only if they're already using streams. 145 public static <T extends @Nullable Object, K, V> 146 Collector<T, ?, ImmutableSetMultimap<K, V>> flatteningToImmutableSetMultimap( 147 Function<? super T, ? extends K> keyFunction, 148 Function<? super T, ? extends Stream<? extends V>> valuesFunction) { 149 return CollectCollectors.flatteningToImmutableSetMultimap(keyFunction, valuesFunction); 150 } 151 152 /** 153 * Returns the empty multimap. 154 * 155 * <p><b>Performance note:</b> the instance returned is a singleton. 156 */ 157 // Casting is safe because the multimap will never hold any elements. 158 @SuppressWarnings("unchecked") 159 public static <K, V> ImmutableSetMultimap<K, V> of() { 160 return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE; 161 } 162 163 /** Returns an immutable multimap containing a single entry. */ 164 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) { 165 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 166 builder.put(k1, v1); 167 return builder.build(); 168 } 169 170 /** 171 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 172 * an entry (according to {@link Object#equals}) after the first are ignored. 173 */ 174 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) { 175 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 176 builder.put(k1, v1); 177 builder.put(k2, v2); 178 return builder.build(); 179 } 180 181 /** 182 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 183 * an entry (according to {@link Object#equals}) after the first are ignored. 184 */ 185 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 186 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 187 builder.put(k1, v1); 188 builder.put(k2, v2); 189 builder.put(k3, v3); 190 return builder.build(); 191 } 192 193 /** 194 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 195 * an entry (according to {@link Object#equals}) after the first are ignored. 196 */ 197 public static <K, V> ImmutableSetMultimap<K, V> of( 198 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 199 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 200 builder.put(k1, v1); 201 builder.put(k2, v2); 202 builder.put(k3, v3); 203 builder.put(k4, v4); 204 return builder.build(); 205 } 206 207 /** 208 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 209 * an entry (according to {@link Object#equals}) after the first are ignored. 210 */ 211 public static <K, V> ImmutableSetMultimap<K, V> of( 212 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 213 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 214 builder.put(k1, v1); 215 builder.put(k2, v2); 216 builder.put(k3, v3); 217 builder.put(k4, v4); 218 builder.put(k5, v5); 219 return builder.build(); 220 } 221 222 // looking for of() with > 5 entries? Use the builder instead. 223 224 /** Returns a new {@link Builder}. */ 225 public static <K, V> Builder<K, V> builder() { 226 return new Builder<>(); 227 } 228 229 /** 230 * Returns a new builder with a hint for how many distinct keys are expected to be added. The 231 * generated builder is equivalent to that returned by {@link #builder}, but may perform better if 232 * {@code expectedKeys} is a good estimate. 233 * 234 * @throws IllegalArgumentException if {@code expectedKeys} is negative 235 * @since 33.3.0 236 */ 237 public static <K, V> Builder<K, V> builderWithExpectedKeys(int expectedKeys) { 238 checkNonnegative(expectedKeys, "expectedKeys"); 239 return new Builder<>(expectedKeys); 240 } 241 242 /** 243 * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static 244 * final} multimaps ("constant multimaps"). Example: 245 * 246 * {@snippet : 247 * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = 248 * new ImmutableSetMultimap.Builder<String, Integer>() 249 * .put("one", 1) 250 * .putAll("several", 1, 2, 3) 251 * .putAll("many", 1, 2, 3, 4, 5) 252 * .build(); 253 * } 254 * 255 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 256 * multiple multimaps in series. Each multimap contains the key-value mappings in the previously 257 * created multimaps. 258 * 259 * @since 2.0 260 */ 261 public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { 262 /** 263 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 264 * ImmutableSetMultimap#builder}. 265 */ 266 public Builder() {} 267 268 Builder(int expectedKeys) { 269 super(expectedKeys); 270 } 271 272 @Override 273 ImmutableCollection.Builder<V> newValueCollectionBuilderWithExpectedSize(int expectedSize) { 274 return (valueComparator == null) 275 ? ImmutableSet.builderWithExpectedSize(expectedSize) 276 : new ImmutableSortedSet.Builder<V>(valueComparator, expectedSize); 277 } 278 279 @Override 280 int expectedValueCollectionSize(int defaultExpectedValues, Iterable<?> values) { 281 // Only trust the size of `values` if it is a Set and therefore probably already deduplicated. 282 if (values instanceof Set<?>) { 283 Set<?> collection = (Set<?>) values; 284 return max(defaultExpectedValues, collection.size()); 285 } else { 286 return defaultExpectedValues; 287 } 288 } 289 290 /** 291 * {@inheritDoc} 292 * 293 * <p>Note that {@code expectedValuesPerKey} is taken to mean the expected number of 294 * <i>distinct</i> values per key. 295 * 296 * @since 33.3.0 297 */ 298 @CanIgnoreReturnValue 299 @Override 300 public Builder<K, V> expectedValuesPerKey(int expectedValuesPerKey) { 301 super.expectedValuesPerKey(expectedValuesPerKey); 302 return this; 303 } 304 305 /** Adds a key-value mapping to the built multimap if it is not already present. */ 306 @CanIgnoreReturnValue 307 @Override 308 public Builder<K, V> put(K key, V value) { 309 super.put(key, value); 310 return this; 311 } 312 313 /** 314 * Adds an entry to the built multimap if it is not already present. 315 * 316 * @since 11.0 317 */ 318 @CanIgnoreReturnValue 319 @Override 320 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 321 super.put(entry); 322 return this; 323 } 324 325 /** 326 * {@inheritDoc} 327 * 328 * @since 19.0 329 */ 330 @CanIgnoreReturnValue 331 @Override 332 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 333 super.putAll(entries); 334 return this; 335 } 336 337 @CanIgnoreReturnValue 338 @Override 339 public Builder<K, V> putAll(K key, Iterable<? extends V> values) { 340 super.putAll(key, values); 341 return this; 342 } 343 344 @CanIgnoreReturnValue 345 @Override 346 public Builder<K, V> putAll(K key, V... values) { 347 return putAll(key, asList(values)); 348 } 349 350 @CanIgnoreReturnValue 351 @Override 352 public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { 353 for (Entry<? extends K, ? extends Collection<? extends V>> entry : 354 multimap.asMap().entrySet()) { 355 putAll(entry.getKey(), entry.getValue()); 356 } 357 return this; 358 } 359 360 @CanIgnoreReturnValue 361 @Override 362 Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) { 363 super.combine(other); 364 return this; 365 } 366 367 /** 368 * {@inheritDoc} 369 * 370 * @since 8.0 371 */ 372 @CanIgnoreReturnValue 373 @Override 374 public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { 375 super.orderKeysBy(keyComparator); 376 return this; 377 } 378 379 /** 380 * Specifies the ordering of the generated multimap's values for each key. 381 * 382 * <p>If this method is called, the sets returned by the {@code get()} method of the generated 383 * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances. 384 * However, serialization does not preserve that property, though it does maintain the key and 385 * value ordering. 386 * 387 * @since 8.0 388 */ 389 // TODO: Make serialization behavior consistent. 390 @CanIgnoreReturnValue 391 @Override 392 public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { 393 super.orderValuesBy(valueComparator); 394 return this; 395 } 396 397 /** Returns a newly-created immutable set multimap. */ 398 @Override 399 public ImmutableSetMultimap<K, V> build() { 400 if (builderMap == null) { 401 return ImmutableSetMultimap.of(); 402 } 403 Collection<Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries = builderMap.entrySet(); 404 if (keyComparator != null) { 405 mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries); 406 } 407 return fromMapBuilderEntries(mapEntries, valueComparator); 408 } 409 } 410 411 /** 412 * Returns an immutable set multimap containing the same mappings as {@code multimap}. The 413 * generated multimap's key and value orderings correspond to the iteration ordering of the {@code 414 * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are 415 * ignored. 416 * 417 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 418 * safe to do so. The exact circumstances under which a copy will or will not be performed are 419 * undocumented and subject to change. 420 * 421 * @throws NullPointerException if any key or value in {@code multimap} is null 422 */ 423 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 424 Multimap<? extends K, ? extends V> multimap) { 425 return copyOf(multimap, null); 426 } 427 428 private static <K, V> ImmutableSetMultimap<K, V> copyOf( 429 Multimap<? extends K, ? extends V> multimap, 430 @Nullable Comparator<? super V> valueComparator) { 431 checkNotNull(multimap); // eager for GWT 432 if (multimap.isEmpty() && valueComparator == null) { 433 return of(); 434 } 435 436 if (multimap instanceof ImmutableSetMultimap) { 437 @SuppressWarnings("unchecked") // safe since multimap is not writable 438 ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap; 439 if (!kvMultimap.isPartialView()) { 440 return kvMultimap; 441 } 442 } 443 444 return fromMapEntries(multimap.asMap().entrySet(), valueComparator); 445 } 446 447 /** 448 * Returns an immutable multimap containing the specified entries. The returned multimap iterates 449 * over keys in the order they were first encountered in the input, and the values for each key 450 * are iterated in the order they were encountered. If two values for the same key are {@linkplain 451 * Object#equals equal}, the first value encountered is used. 452 * 453 * @throws NullPointerException if any key, value, or entry is null 454 * @since 19.0 455 */ 456 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 457 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 458 return new Builder<K, V>().putAll(entries).build(); 459 } 460 461 /** Creates an ImmutableSetMultimap from an asMap.entrySet. */ 462 static <K, V> ImmutableSetMultimap<K, V> fromMapEntries( 463 Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries, 464 @Nullable Comparator<? super V> valueComparator) { 465 if (mapEntries.isEmpty()) { 466 return of(); 467 } 468 ImmutableMap.Builder<K, ImmutableSet<V>> builder = 469 new ImmutableMap.Builder<>(mapEntries.size()); 470 int size = 0; 471 472 for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) { 473 K key = entry.getKey(); 474 Collection<? extends V> values = entry.getValue(); 475 ImmutableSet<V> set = valueSet(valueComparator, values); 476 if (!set.isEmpty()) { 477 builder.put(key, set); 478 size += set.size(); 479 } 480 } 481 482 return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator); 483 } 484 485 /** Creates an ImmutableSetMultimap from a map to builders. */ 486 static <K, V> ImmutableSetMultimap<K, V> fromMapBuilderEntries( 487 Collection<? extends Map.Entry<K, ImmutableCollection.Builder<V>>> mapEntries, 488 @Nullable Comparator<? super V> valueComparator) { 489 if (mapEntries.isEmpty()) { 490 return of(); 491 } 492 ImmutableMap.Builder<K, ImmutableSet<V>> builder = 493 new ImmutableMap.Builder<>(mapEntries.size()); 494 int size = 0; 495 496 for (Entry<K, ImmutableCollection.Builder<V>> entry : mapEntries) { 497 K key = entry.getKey(); 498 ImmutableSet.Builder<? extends V> values = (ImmutableSet.Builder<V>) entry.getValue(); 499 // If orderValuesBy got called at the very end, we may need to do the ImmutableSet to 500 // ImmutableSortedSet copy for each of these. 501 ImmutableSet<V> set = valueSet(valueComparator, values.build()); 502 if (!set.isEmpty()) { 503 builder.put(key, set); 504 size += set.size(); 505 } 506 } 507 508 return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator); 509 } 510 511 /** 512 * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for 513 * values. 514 */ 515 private final transient ImmutableSet<V> emptySet; 516 517 ImmutableSetMultimap( 518 ImmutableMap<K, ImmutableSet<V>> map, 519 int size, 520 @Nullable Comparator<? super V> valueComparator) { 521 super(map, size); 522 this.emptySet = emptySet(valueComparator); 523 } 524 525 // views 526 527 /** 528 * Returns an immutable set of the values for the given key. If no mappings in the multimap have 529 * the provided key, an empty immutable set is returned. The values are in the same order as the 530 * parameters used to build this multimap. 531 */ 532 @Override 533 public ImmutableSet<V> get(K key) { 534 // This cast is safe as its type is known in constructor. 535 ImmutableSet<V> set = (ImmutableSet<V>) map.get(key); 536 return MoreObjects.firstNonNull(set, emptySet); 537 } 538 539 @LazyInit @RetainedWith private transient @Nullable ImmutableSetMultimap<V, K> inverse; 540 541 /** 542 * {@inheritDoc} 543 * 544 * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and 545 * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code 546 * ImmutableMultimap} specified in the {@code ImmutableMultimap} class. 547 */ 548 @Override 549 public ImmutableSetMultimap<V, K> inverse() { 550 ImmutableSetMultimap<V, K> result = inverse; 551 return (result == null) ? (inverse = invert()) : result; 552 } 553 554 private ImmutableSetMultimap<V, K> invert() { 555 Builder<V, K> builder = builder(); 556 for (Entry<K, V> entry : entries()) { 557 builder.put(entry.getValue(), entry.getKey()); 558 } 559 ImmutableSetMultimap<V, K> invertedMultimap = builder.build(); 560 invertedMultimap.inverse = this; 561 return invertedMultimap; 562 } 563 564 /** 565 * Guaranteed to throw an exception and leave the multimap unmodified. 566 * 567 * @throws UnsupportedOperationException always 568 * @deprecated Unsupported operation. 569 */ 570 @CanIgnoreReturnValue 571 @Deprecated 572 @Override 573 @DoNotCall("Always throws UnsupportedOperationException") 574 public final ImmutableSet<V> removeAll(@Nullable Object key) { 575 throw new UnsupportedOperationException(); 576 } 577 578 /** 579 * Guaranteed to throw an exception and leave the multimap unmodified. 580 * 581 * @throws UnsupportedOperationException always 582 * @deprecated Unsupported operation. 583 */ 584 @CanIgnoreReturnValue 585 @Deprecated 586 @Override 587 @DoNotCall("Always throws UnsupportedOperationException") 588 public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) { 589 throw new UnsupportedOperationException(); 590 } 591 592 @LazyInit @RetainedWith private transient @Nullable ImmutableSet<Entry<K, V>> entries; 593 594 /** 595 * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses 596 * the values for the first key, the values for the second key, and so on. 597 */ 598 @Override 599 public ImmutableSet<Entry<K, V>> entries() { 600 ImmutableSet<Entry<K, V>> result = entries; 601 return result == null ? (entries = new EntrySet<>(this)) : result; 602 } 603 604 private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> { 605 @Weak private final transient ImmutableSetMultimap<K, V> multimap; 606 607 EntrySet(ImmutableSetMultimap<K, V> multimap) { 608 this.multimap = multimap; 609 } 610 611 @Override 612 public boolean contains(@Nullable Object object) { 613 if (object instanceof Entry) { 614 Entry<?, ?> entry = (Entry<?, ?>) object; 615 return multimap.containsEntry(entry.getKey(), entry.getValue()); 616 } 617 return false; 618 } 619 620 @Override 621 public int size() { 622 return multimap.size(); 623 } 624 625 @Override 626 public UnmodifiableIterator<Entry<K, V>> iterator() { 627 return multimap.entryIterator(); 628 } 629 630 @Override 631 boolean isPartialView() { 632 return false; 633 } 634 635 // redeclare to help optimizers with b/310253115 636 @SuppressWarnings("RedundantOverride") 637 @Override 638 @J2ktIncompatible // serialization 639 @GwtIncompatible // serialization 640 Object writeReplace() { 641 return super.writeReplace(); 642 } 643 } 644 645 private static <V> ImmutableSet<V> valueSet( 646 @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) { 647 return (valueComparator == null) 648 ? ImmutableSet.copyOf(values) 649 : ImmutableSortedSet.copyOf(valueComparator, values); 650 } 651 652 private static <V> ImmutableSet<V> emptySet(@Nullable Comparator<? super V> valueComparator) { 653 return (valueComparator == null) 654 ? ImmutableSet.<V>of() 655 : ImmutableSortedSet.<V>emptySet(valueComparator); 656 } 657 658 private static <V> ImmutableSet.Builder<V> valuesBuilder( 659 @Nullable Comparator<? super V> valueComparator) { 660 return (valueComparator == null) 661 ? new ImmutableSet.Builder<V>() 662 : new ImmutableSortedSet.Builder<V>(valueComparator); 663 } 664 665 /** 666 * @serialData number of distinct keys, and then for each distinct key: the key, the number of 667 * values for that key, and the key's values 668 */ 669 @GwtIncompatible // java.io.ObjectOutputStream 670 @J2ktIncompatible 671 private void writeObject(ObjectOutputStream stream) throws IOException { 672 stream.defaultWriteObject(); 673 stream.writeObject(valueComparator()); 674 Serialization.writeMultimap(this, stream); 675 } 676 677 @Nullable Comparator<? super V> valueComparator() { 678 return emptySet instanceof ImmutableSortedSet 679 ? ((ImmutableSortedSet<V>) emptySet).comparator() 680 : null; 681 } 682 683 @GwtIncompatible // java serialization 684 @J2ktIncompatible 685 private static final class SetFieldSettersHolder { 686 static final Serialization.FieldSetter<? super ImmutableSetMultimap<?, ?>> 687 EMPTY_SET_FIELD_SETTER = 688 Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet"); 689 } 690 691 @GwtIncompatible // java.io.ObjectInputStream 692 @J2ktIncompatible 693 // Serialization type safety is at the caller's mercy. 694 @SuppressWarnings("unchecked") 695 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 696 stream.defaultReadObject(); 697 Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject(); 698 int keyCount = stream.readInt(); 699 if (keyCount < 0) { 700 throw new InvalidObjectException("Invalid key count " + keyCount); 701 } 702 ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder(); 703 int tmpSize = 0; 704 705 for (int i = 0; i < keyCount; i++) { 706 Object key = requireNonNull(stream.readObject()); 707 int valueCount = stream.readInt(); 708 if (valueCount <= 0) { 709 throw new InvalidObjectException("Invalid value count " + valueCount); 710 } 711 712 ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator); 713 for (int j = 0; j < valueCount; j++) { 714 valuesBuilder.add(requireNonNull(stream.readObject())); 715 } 716 ImmutableSet<Object> valueSet = valuesBuilder.build(); 717 if (valueSet.size() != valueCount) { 718 throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key); 719 } 720 builder.put(key, valueSet); 721 tmpSize += valueCount; 722 } 723 724 ImmutableMap<Object, ImmutableSet<Object>> tmpMap; 725 try { 726 tmpMap = builder.buildOrThrow(); 727 } catch (IllegalArgumentException e) { 728 throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); 729 } 730 731 FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); 732 FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); 733 SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator)); 734 } 735 736 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; 737}