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