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; 020 021import com.google.common.annotations.GwtCompatible; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.annotations.J2ktIncompatible; 024import com.google.common.base.MoreObjects; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import com.google.errorprone.annotations.DoNotCall; 027import com.google.errorprone.annotations.concurrent.LazyInit; 028import com.google.j2objc.annotations.RetainedWith; 029import com.google.j2objc.annotations.Weak; 030import java.io.IOException; 031import java.io.InvalidObjectException; 032import java.io.ObjectInputStream; 033import java.io.ObjectOutputStream; 034import java.util.Arrays; 035import java.util.Collection; 036import java.util.Comparator; 037import java.util.Map; 038import java.util.Map.Entry; 039import javax.annotation.CheckForNull; 040 041/** 042 * A {@link SetMultimap} whose contents will never change, with many other important properties 043 * detailed at {@link ImmutableCollection}. 044 * 045 * <p><b>Warning:</b> As in all {@link SetMultimap}s, do not modify either a key <i>or a value</i> 046 * of a {@code ImmutableSetMultimap} in a way that affects its {@link Object#equals} behavior. 047 * Undefined behavior and bugs will result. 048 * 049 * <p>See the Guava User Guide article on <a href= 050 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained">immutable collections</a>. 051 * 052 * @author Mike Ward 053 * @since 2.0 054 */ 055@GwtCompatible(serializable = true, emulated = true) 056@ElementTypesAreNonnullByDefault 057public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V> 058 implements SetMultimap<K, V> { 059 060 /** 061 * Returns the empty multimap. 062 * 063 * <p><b>Performance note:</b> the instance returned is a singleton. 064 */ 065 // Casting is safe because the multimap will never hold any elements. 066 @SuppressWarnings("unchecked") 067 public static <K, V> ImmutableSetMultimap<K, V> of() { 068 return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE; 069 } 070 071 /** Returns an immutable multimap containing a single entry. */ 072 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) { 073 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 074 builder.put(k1, v1); 075 return builder.build(); 076 } 077 078 /** 079 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 080 * an entry (according to {@link Object#equals}) after the first are ignored. 081 */ 082 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) { 083 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 084 builder.put(k1, v1); 085 builder.put(k2, v2); 086 return builder.build(); 087 } 088 089 /** 090 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 091 * an entry (according to {@link Object#equals}) after the first are ignored. 092 */ 093 public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 094 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 095 builder.put(k1, v1); 096 builder.put(k2, v2); 097 builder.put(k3, v3); 098 return builder.build(); 099 } 100 101 /** 102 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 103 * an entry (according to {@link Object#equals}) after the first are ignored. 104 */ 105 public static <K, V> ImmutableSetMultimap<K, V> of( 106 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 107 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 108 builder.put(k1, v1); 109 builder.put(k2, v2); 110 builder.put(k3, v3); 111 builder.put(k4, v4); 112 return builder.build(); 113 } 114 115 /** 116 * Returns an immutable multimap containing the given entries, in order. Repeated occurrences of 117 * an entry (according to {@link Object#equals}) after the first are ignored. 118 */ 119 public static <K, V> ImmutableSetMultimap<K, V> of( 120 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 121 ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); 122 builder.put(k1, v1); 123 builder.put(k2, v2); 124 builder.put(k3, v3); 125 builder.put(k4, v4); 126 builder.put(k5, v5); 127 return builder.build(); 128 } 129 130 // looking for of() with > 5 entries? Use the builder instead. 131 132 /** Returns a new {@link Builder}. */ 133 public static <K, V> Builder<K, V> builder() { 134 return new Builder<>(); 135 } 136 137 /** 138 * A builder for creating immutable {@code SetMultimap} instances, especially {@code public static 139 * final} multimaps ("constant multimaps"). Example: 140 * 141 * <pre>{@code 142 * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = 143 * new ImmutableSetMultimap.Builder<String, Integer>() 144 * .put("one", 1) 145 * .putAll("several", 1, 2, 3) 146 * .putAll("many", 1, 2, 3, 4, 5) 147 * .build(); 148 * }</pre> 149 * 150 * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build 151 * multiple multimaps in series. Each multimap contains the key-value mappings in the previously 152 * created multimaps. 153 * 154 * @since 2.0 155 */ 156 public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { 157 /** 158 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 159 * ImmutableSetMultimap#builder}. 160 */ 161 public Builder() { 162 super(); 163 } 164 165 @Override 166 Collection<V> newMutableValueCollection() { 167 return Platform.preservesInsertionOrderOnAddsSet(); 168 } 169 170 /** Adds a key-value mapping to the built multimap if it is not already present. */ 171 @CanIgnoreReturnValue 172 @Override 173 public Builder<K, V> put(K key, V value) { 174 super.put(key, value); 175 return this; 176 } 177 178 /** 179 * Adds an entry to the built multimap if it is not already present. 180 * 181 * @since 11.0 182 */ 183 @CanIgnoreReturnValue 184 @Override 185 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 186 super.put(entry); 187 return this; 188 } 189 190 /** 191 * {@inheritDoc} 192 * 193 * @since 19.0 194 */ 195 @CanIgnoreReturnValue 196 @Override 197 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 198 super.putAll(entries); 199 return this; 200 } 201 202 @CanIgnoreReturnValue 203 @Override 204 public Builder<K, V> putAll(K key, Iterable<? extends V> values) { 205 super.putAll(key, values); 206 return this; 207 } 208 209 @CanIgnoreReturnValue 210 @Override 211 public Builder<K, V> putAll(K key, V... values) { 212 return putAll(key, Arrays.asList(values)); 213 } 214 215 @CanIgnoreReturnValue 216 @Override 217 public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { 218 for (Entry<? extends K, ? extends Collection<? extends V>> entry : 219 multimap.asMap().entrySet()) { 220 putAll(entry.getKey(), entry.getValue()); 221 } 222 return this; 223 } 224 225 @CanIgnoreReturnValue 226 @Override 227 Builder<K, V> combine(ImmutableMultimap.Builder<K, V> other) { 228 super.combine(other); 229 return this; 230 } 231 232 /** 233 * {@inheritDoc} 234 * 235 * @since 8.0 236 */ 237 @CanIgnoreReturnValue 238 @Override 239 public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { 240 super.orderKeysBy(keyComparator); 241 return this; 242 } 243 244 /** 245 * Specifies the ordering of the generated multimap's values for each key. 246 * 247 * <p>If this method is called, the sets returned by the {@code get()} method of the generated 248 * multimap and its {@link Multimap#asMap()} view are {@link ImmutableSortedSet} instances. 249 * However, serialization does not preserve that property, though it does maintain the key and 250 * value ordering. 251 * 252 * @since 8.0 253 */ 254 // TODO: Make serialization behavior consistent. 255 @CanIgnoreReturnValue 256 @Override 257 public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { 258 super.orderValuesBy(valueComparator); 259 return this; 260 } 261 262 /** Returns a newly-created immutable set multimap. */ 263 @Override 264 public ImmutableSetMultimap<K, V> build() { 265 Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet(); 266 if (keyComparator != null) { 267 mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries); 268 } 269 return fromMapEntries(mapEntries, valueComparator); 270 } 271 } 272 273 /** 274 * Returns an immutable set multimap containing the same mappings as {@code multimap}. The 275 * generated multimap's key and value orderings correspond to the iteration ordering of the {@code 276 * multimap.asMap()} view. Repeated occurrences of an entry in the multimap after the first are 277 * ignored. 278 * 279 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 280 * safe to do so. The exact circumstances under which a copy will or will not be performed are 281 * undocumented and subject to change. 282 * 283 * @throws NullPointerException if any key or value in {@code multimap} is null 284 */ 285 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 286 Multimap<? extends K, ? extends V> multimap) { 287 return copyOf(multimap, null); 288 } 289 290 private static <K, V> ImmutableSetMultimap<K, V> copyOf( 291 Multimap<? extends K, ? extends V> multimap, 292 @CheckForNull Comparator<? super V> valueComparator) { 293 checkNotNull(multimap); // eager for GWT 294 if (multimap.isEmpty() && valueComparator == null) { 295 return of(); 296 } 297 298 if (multimap instanceof ImmutableSetMultimap) { 299 @SuppressWarnings("unchecked") // safe since multimap is not writable 300 ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap; 301 if (!kvMultimap.isPartialView()) { 302 return kvMultimap; 303 } 304 } 305 306 return fromMapEntries(multimap.asMap().entrySet(), valueComparator); 307 } 308 309 /** 310 * Returns an immutable multimap containing the specified entries. The returned multimap iterates 311 * over keys in the order they were first encountered in the input, and the values for each key 312 * are iterated in the order they were encountered. If two values for the same key are {@linkplain 313 * Object#equals equal}, the first value encountered is used. 314 * 315 * @throws NullPointerException if any key, value, or entry is null 316 * @since 19.0 317 */ 318 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 319 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 320 return new Builder<K, V>().putAll(entries).build(); 321 } 322 323 /** Creates an ImmutableSetMultimap from an asMap.entrySet. */ 324 static <K, V> ImmutableSetMultimap<K, V> fromMapEntries( 325 Collection<? extends Map.Entry<? extends K, ? extends Collection<? extends V>>> mapEntries, 326 @CheckForNull Comparator<? super V> valueComparator) { 327 if (mapEntries.isEmpty()) { 328 return of(); 329 } 330 ImmutableMap.Builder<K, ImmutableSet<V>> builder = 331 new ImmutableMap.Builder<>(mapEntries.size()); 332 int size = 0; 333 334 for (Entry<? extends K, ? extends Collection<? extends V>> entry : mapEntries) { 335 K key = entry.getKey(); 336 Collection<? extends V> values = entry.getValue(); 337 ImmutableSet<V> set = valueSet(valueComparator, values); 338 if (!set.isEmpty()) { 339 builder.put(key, set); 340 size += set.size(); 341 } 342 } 343 344 return new ImmutableSetMultimap<>(builder.buildOrThrow(), size, valueComparator); 345 } 346 347 /** 348 * Returned by get() when a missing key is provided. Also holds the comparator, if any, used for 349 * values. 350 */ 351 private final transient ImmutableSet<V> emptySet; 352 353 ImmutableSetMultimap( 354 ImmutableMap<K, ImmutableSet<V>> map, 355 int size, 356 @CheckForNull Comparator<? super V> valueComparator) { 357 super(map, size); 358 this.emptySet = emptySet(valueComparator); 359 } 360 361 // views 362 363 /** 364 * Returns an immutable set of the values for the given key. If no mappings in the multimap have 365 * the provided key, an empty immutable set is returned. The values are in the same order as the 366 * parameters used to build this multimap. 367 */ 368 @Override 369 public ImmutableSet<V> get(K key) { 370 // This cast is safe as its type is known in constructor. 371 ImmutableSet<V> set = (ImmutableSet<V>) map.get(key); 372 return MoreObjects.firstNonNull(set, emptySet); 373 } 374 375 @LazyInit @RetainedWith @CheckForNull private transient ImmutableSetMultimap<V, K> inverse; 376 377 /** 378 * {@inheritDoc} 379 * 380 * <p>Because an inverse of a set multimap cannot contain multiple pairs with the same key and 381 * value, this method returns an {@code ImmutableSetMultimap} rather than the {@code 382 * ImmutableMultimap} specified in the {@code ImmutableMultimap} class. 383 */ 384 @Override 385 public ImmutableSetMultimap<V, K> inverse() { 386 ImmutableSetMultimap<V, K> result = inverse; 387 return (result == null) ? (inverse = invert()) : result; 388 } 389 390 private ImmutableSetMultimap<V, K> invert() { 391 Builder<V, K> builder = builder(); 392 for (Entry<K, V> entry : entries()) { 393 builder.put(entry.getValue(), entry.getKey()); 394 } 395 ImmutableSetMultimap<V, K> invertedMultimap = builder.build(); 396 invertedMultimap.inverse = this; 397 return invertedMultimap; 398 } 399 400 /** 401 * Guaranteed to throw an exception and leave the multimap unmodified. 402 * 403 * @throws UnsupportedOperationException always 404 * @deprecated Unsupported operation. 405 */ 406 @CanIgnoreReturnValue 407 @Deprecated 408 @Override 409 @DoNotCall("Always throws UnsupportedOperationException") 410 public final ImmutableSet<V> removeAll(@CheckForNull Object key) { 411 throw new UnsupportedOperationException(); 412 } 413 414 /** 415 * Guaranteed to throw an exception and leave the multimap unmodified. 416 * 417 * @throws UnsupportedOperationException always 418 * @deprecated Unsupported operation. 419 */ 420 @CanIgnoreReturnValue 421 @Deprecated 422 @Override 423 @DoNotCall("Always throws UnsupportedOperationException") 424 public final ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) { 425 throw new UnsupportedOperationException(); 426 } 427 428 @LazyInit @RetainedWith @CheckForNull private transient ImmutableSet<Entry<K, V>> entries; 429 430 /** 431 * Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses 432 * the values for the first key, the values for the second key, and so on. 433 */ 434 @Override 435 public ImmutableSet<Entry<K, V>> entries() { 436 ImmutableSet<Entry<K, V>> result = entries; 437 return result == null ? (entries = new EntrySet<>(this)) : result; 438 } 439 440 private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> { 441 @Weak private final transient ImmutableSetMultimap<K, V> multimap; 442 443 EntrySet(ImmutableSetMultimap<K, V> multimap) { 444 this.multimap = multimap; 445 } 446 447 @Override 448 public boolean contains(@CheckForNull Object object) { 449 if (object instanceof Entry) { 450 Entry<?, ?> entry = (Entry<?, ?>) object; 451 return multimap.containsEntry(entry.getKey(), entry.getValue()); 452 } 453 return false; 454 } 455 456 @Override 457 public int size() { 458 return multimap.size(); 459 } 460 461 @Override 462 public UnmodifiableIterator<Entry<K, V>> iterator() { 463 return multimap.entryIterator(); 464 } 465 466 @Override 467 boolean isPartialView() { 468 return false; 469 } 470 } 471 472 private static <V> ImmutableSet<V> valueSet( 473 @CheckForNull Comparator<? super V> valueComparator, Collection<? extends V> values) { 474 return (valueComparator == null) 475 ? ImmutableSet.copyOf(values) 476 : ImmutableSortedSet.copyOf(valueComparator, values); 477 } 478 479 private static <V> ImmutableSet<V> emptySet(@CheckForNull Comparator<? super V> valueComparator) { 480 return (valueComparator == null) 481 ? ImmutableSet.<V>of() 482 : ImmutableSortedSet.<V>emptySet(valueComparator); 483 } 484 485 private static <V> ImmutableSet.Builder<V> valuesBuilder( 486 @CheckForNull Comparator<? super V> valueComparator) { 487 return (valueComparator == null) 488 ? new ImmutableSet.Builder<V>() 489 : new ImmutableSortedSet.Builder<V>(valueComparator); 490 } 491 492 /** 493 * @serialData number of distinct keys, and then for each distinct key: the key, the number of 494 * values for that key, and the key's values 495 */ 496 @GwtIncompatible // java.io.ObjectOutputStream 497 @J2ktIncompatible 498 private void writeObject(ObjectOutputStream stream) throws IOException { 499 stream.defaultWriteObject(); 500 stream.writeObject(valueComparator()); 501 Serialization.writeMultimap(this, stream); 502 } 503 504 @CheckForNull 505 Comparator<? super V> valueComparator() { 506 return emptySet instanceof ImmutableSortedSet 507 ? ((ImmutableSortedSet<V>) emptySet).comparator() 508 : null; 509 } 510 511 @GwtIncompatible // java serialization 512 @J2ktIncompatible 513 private static final class SetFieldSettersHolder { 514 static final Serialization.FieldSetter<ImmutableSetMultimap> EMPTY_SET_FIELD_SETTER = 515 Serialization.getFieldSetter(ImmutableSetMultimap.class, "emptySet"); 516 } 517 518 @GwtIncompatible // java.io.ObjectInputStream 519 @J2ktIncompatible 520 // Serialization type safety is at the caller's mercy. 521 @SuppressWarnings("unchecked") 522 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 523 stream.defaultReadObject(); 524 Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject(); 525 int keyCount = stream.readInt(); 526 if (keyCount < 0) { 527 throw new InvalidObjectException("Invalid key count " + keyCount); 528 } 529 ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder(); 530 int tmpSize = 0; 531 532 for (int i = 0; i < keyCount; i++) { 533 Object key = stream.readObject(); 534 int valueCount = stream.readInt(); 535 if (valueCount <= 0) { 536 throw new InvalidObjectException("Invalid value count " + valueCount); 537 } 538 539 ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator); 540 for (int j = 0; j < valueCount; j++) { 541 valuesBuilder.add(stream.readObject()); 542 } 543 ImmutableSet<Object> valueSet = valuesBuilder.build(); 544 if (valueSet.size() != valueCount) { 545 throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key); 546 } 547 builder.put(key, valueSet); 548 tmpSize += valueCount; 549 } 550 551 ImmutableMap<Object, ImmutableSet<Object>> tmpMap; 552 try { 553 tmpMap = builder.buildOrThrow(); 554 } catch (IllegalArgumentException e) { 555 throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); 556 } 557 558 FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); 559 FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); 560 SetFieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator)); 561 } 562 563 @GwtIncompatible // not needed in emulated source. 564 @J2ktIncompatible 565 private static final long serialVersionUID = 0; 566}