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