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.j2objc.annotations.Weak; 026 027import java.io.IOException; 028import java.io.InvalidObjectException; 029import java.io.ObjectInputStream; 030import java.io.ObjectOutputStream; 031import java.util.Arrays; 032import java.util.Collection; 033import java.util.Comparator; 034import java.util.List; 035import java.util.Map; 036import java.util.Map.Entry; 037 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<K, V>(); 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 @Override 168 public Builder<K, V> put(K key, V value) { 169 builderMultimap.put(checkNotNull(key), checkNotNull(value)); 170 return this; 171 } 172 173 /** 174 * Adds an entry to the built multimap if it is not already present. 175 * 176 * @since 11.0 177 */ 178 @Override 179 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 180 builderMultimap.put(checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); 181 return this; 182 } 183 184 /** 185 * {@inheritDoc} 186 * 187 * @since 19.0 188 */ 189 @Beta 190 @Override 191 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 192 super.putAll(entries); 193 return this; 194 } 195 196 @Override 197 public Builder<K, V> putAll(K key, Iterable<? extends V> values) { 198 Collection<V> collection = builderMultimap.get(checkNotNull(key)); 199 for (V value : values) { 200 collection.add(checkNotNull(value)); 201 } 202 return this; 203 } 204 205 @Override 206 public Builder<K, V> putAll(K key, V... values) { 207 return putAll(key, Arrays.asList(values)); 208 } 209 210 @Override 211 public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) { 212 for (Entry<? extends K, ? extends Collection<? extends V>> entry : 213 multimap.asMap().entrySet()) { 214 putAll(entry.getKey(), entry.getValue()); 215 } 216 return this; 217 } 218 219 /** 220 * {@inheritDoc} 221 * 222 * @since 8.0 223 */ 224 @Override 225 public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { 226 this.keyComparator = checkNotNull(keyComparator); 227 return this; 228 } 229 230 /** 231 * Specifies the ordering of the generated multimap's values for each key. 232 * 233 * <p>If this method is called, the sets returned by the {@code get()} 234 * method of the generated multimap and its {@link Multimap#asMap()} view 235 * are {@link ImmutableSortedSet} instances. However, serialization does not 236 * preserve that property, though it does maintain the key and value 237 * ordering. 238 * 239 * @since 8.0 240 */ 241 // TODO: Make serialization behavior consistent. 242 @Override 243 public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { 244 super.orderValuesBy(valueComparator); 245 return this; 246 } 247 248 /** 249 * Returns a newly-created immutable set multimap. 250 */ 251 @Override 252 public ImmutableSetMultimap<K, V> build() { 253 if (keyComparator != null) { 254 Multimap<K, V> sortedCopy = 255 MultimapBuilder.linkedHashKeys().linkedHashSetValues().<K, V>build(); 256 List<Map.Entry<K, Collection<V>>> entries = 257 Ordering.from(keyComparator) 258 .<K>onKeys() 259 .immutableSortedCopy(builderMultimap.asMap().entrySet()); 260 for (Map.Entry<K, Collection<V>> entry : entries) { 261 sortedCopy.putAll(entry.getKey(), entry.getValue()); 262 } 263 builderMultimap = sortedCopy; 264 } 265 return copyOf(builderMultimap, valueComparator); 266 } 267 } 268 269 /** 270 * Returns an immutable set multimap containing the same mappings as 271 * {@code multimap}. The generated multimap's key and value orderings 272 * correspond to the iteration ordering of the {@code multimap.asMap()} view. 273 * Repeated occurrences of an entry in the multimap after the first are 274 * ignored. 275 * 276 * <p>Despite the method name, this method attempts to avoid actually copying 277 * the data when it is safe to do so. The exact circumstances under which a 278 * copy will or will not be performed are undocumented and subject to change. 279 * 280 * @throws NullPointerException if any key or value in {@code multimap} is 281 * null 282 */ 283 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 284 Multimap<? extends K, ? extends V> multimap) { 285 return copyOf(multimap, null); 286 } 287 288 private static <K, V> ImmutableSetMultimap<K, V> copyOf( 289 Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) { 290 checkNotNull(multimap); // eager for GWT 291 if (multimap.isEmpty() && valueComparator == null) { 292 return of(); 293 } 294 295 if (multimap instanceof ImmutableSetMultimap) { 296 @SuppressWarnings("unchecked") // safe since multimap is not writable 297 ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap; 298 if (!kvMultimap.isPartialView()) { 299 return kvMultimap; 300 } 301 } 302 303 ImmutableMap.Builder<K, ImmutableSet<V>> builder = 304 new ImmutableMap.Builder<K, ImmutableSet<V>>(multimap.asMap().size()); 305 int size = 0; 306 307 for (Entry<? extends K, ? extends Collection<? extends V>> entry : 308 multimap.asMap().entrySet()) { 309 K key = entry.getKey(); 310 Collection<? extends V> values = entry.getValue(); 311 ImmutableSet<V> set = valueSet(valueComparator, values); 312 if (!set.isEmpty()) { 313 builder.put(key, set); 314 size += set.size(); 315 } 316 } 317 318 return new ImmutableSetMultimap<K, V>(builder.build(), size, valueComparator); 319 } 320 321 /** 322 * Returns an immutable multimap containing the specified entries. The 323 * returned multimap iterates over keys in the order they were first 324 * encountered in the input, and the values for each key are iterated in the 325 * order they were encountered. If two values for the same key are 326 * {@linkplain Object#equals equal}, the first value encountered is used. 327 * 328 * @throws NullPointerException if any key, value, or entry is null 329 * @since 19.0 330 */ 331 @Beta 332 public static <K, V> ImmutableSetMultimap<K, V> copyOf( 333 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 334 return new Builder<K, V>().putAll(entries).build(); 335 } 336 337 /** 338 * Returned by get() when a missing key is provided. Also holds the 339 * comparator, if any, used for values. 340 */ 341 private final transient ImmutableSet<V> emptySet; 342 343 ImmutableSetMultimap( 344 ImmutableMap<K, ImmutableSet<V>> map, 345 int size, 346 @Nullable Comparator<? super V> valueComparator) { 347 super(map, size); 348 this.emptySet = emptySet(valueComparator); 349 } 350 351 // views 352 353 /** 354 * Returns an immutable set of the values for the given key. If no mappings 355 * in the multimap have the provided key, an empty immutable set is returned. 356 * The values are in the same order as the parameters used to build this 357 * multimap. 358 */ 359 @Override 360 public ImmutableSet<V> get(@Nullable K key) { 361 // This cast is safe as its type is known in constructor. 362 ImmutableSet<V> set = (ImmutableSet<V>) map.get(key); 363 return MoreObjects.firstNonNull(set, emptySet); 364 } 365 366 private transient ImmutableSetMultimap<V, K> inverse; 367 368 /** 369 * {@inheritDoc} 370 * 371 * <p>Because an inverse of a set multimap cannot contain multiple pairs with 372 * the same key and value, this method returns an {@code ImmutableSetMultimap} 373 * rather than the {@code ImmutableMultimap} specified in the {@code 374 * ImmutableMultimap} class. 375 * 376 * @since 11.0 377 */ 378 public ImmutableSetMultimap<V, K> inverse() { 379 ImmutableSetMultimap<V, K> result = inverse; 380 return (result == null) ? (inverse = invert()) : result; 381 } 382 383 private ImmutableSetMultimap<V, K> invert() { 384 Builder<V, K> builder = builder(); 385 for (Entry<K, V> entry : entries()) { 386 builder.put(entry.getValue(), entry.getKey()); 387 } 388 ImmutableSetMultimap<V, K> invertedMultimap = builder.build(); 389 invertedMultimap.inverse = this; 390 return invertedMultimap; 391 } 392 393 /** 394 * Guaranteed to throw an exception and leave the multimap unmodified. 395 * 396 * @throws UnsupportedOperationException always 397 * @deprecated Unsupported operation. 398 */ 399 @Deprecated 400 @Override 401 public ImmutableSet<V> removeAll(Object key) { 402 throw new UnsupportedOperationException(); 403 } 404 405 /** 406 * Guaranteed to throw an exception and leave the multimap unmodified. 407 * 408 * @throws UnsupportedOperationException always 409 * @deprecated Unsupported operation. 410 */ 411 @Deprecated 412 @Override 413 public ImmutableSet<V> replaceValues(K key, Iterable<? extends V> values) { 414 throw new UnsupportedOperationException(); 415 } 416 417 private transient ImmutableSet<Entry<K, V>> entries; 418 419 /** 420 * Returns an immutable collection of all key-value pairs in the multimap. 421 * Its iterator traverses the values for the first key, the values for the 422 * second key, and so on. 423 */ 424 @Override 425 public ImmutableSet<Entry<K, V>> entries() { 426 ImmutableSet<Entry<K, V>> result = entries; 427 return result == null 428 ? (entries = new EntrySet<K, V>(this)) 429 : result; 430 } 431 432 private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> { 433 @Weak private final transient ImmutableSetMultimap<K, V> multimap; 434 435 EntrySet(ImmutableSetMultimap<K, V> multimap) { 436 this.multimap = multimap; 437 } 438 439 @Override 440 public boolean contains(@Nullable Object object) { 441 if (object instanceof Entry) { 442 Entry<?, ?> entry = (Entry<?, ?>) object; 443 return multimap.containsEntry(entry.getKey(), entry.getValue()); 444 } 445 return false; 446 } 447 448 @Override 449 public int size() { 450 return multimap.size(); 451 } 452 453 @Override 454 public UnmodifiableIterator<Entry<K, V>> iterator() { 455 return multimap.entryIterator(); 456 } 457 458 @Override 459 boolean isPartialView() { 460 return false; 461 } 462 } 463 464 private static <V> ImmutableSet<V> valueSet( 465 @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) { 466 return (valueComparator == null) 467 ? ImmutableSet.copyOf(values) 468 : ImmutableSortedSet.copyOf(valueComparator, values); 469 } 470 471 private static <V> ImmutableSet<V> emptySet(@Nullable Comparator<? super V> valueComparator) { 472 return (valueComparator == null) 473 ? ImmutableSet.<V>of() 474 : ImmutableSortedSet.<V>emptySet(valueComparator); 475 } 476 477 private static <V> ImmutableSet.Builder<V> valuesBuilder( 478 @Nullable Comparator<? super V> valueComparator) { 479 return (valueComparator == null) 480 ? new ImmutableSet.Builder<V>() 481 : new ImmutableSortedSet.Builder<V>(valueComparator); 482 } 483 484 /** 485 * @serialData number of distinct keys, and then for each distinct key: the 486 * key, the number of values for that key, and the key's values 487 */ 488 @GwtIncompatible("java.io.ObjectOutputStream") 489 private void writeObject(ObjectOutputStream stream) throws IOException { 490 stream.defaultWriteObject(); 491 stream.writeObject(valueComparator()); 492 Serialization.writeMultimap(this, stream); 493 } 494 495 @Nullable 496 Comparator<? super V> valueComparator() { 497 return emptySet instanceof ImmutableSortedSet 498 ? ((ImmutableSortedSet<V>) emptySet).comparator() 499 : null; 500 } 501 502 @GwtIncompatible("java.io.ObjectInputStream") 503 // Serialization type safety is at the caller's mercy. 504 @SuppressWarnings("unchecked") 505 private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { 506 stream.defaultReadObject(); 507 Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject(); 508 int keyCount = stream.readInt(); 509 if (keyCount < 0) { 510 throw new InvalidObjectException("Invalid key count " + keyCount); 511 } 512 ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder(); 513 int tmpSize = 0; 514 515 for (int i = 0; i < keyCount; i++) { 516 Object key = stream.readObject(); 517 int valueCount = stream.readInt(); 518 if (valueCount <= 0) { 519 throw new InvalidObjectException("Invalid value count " + valueCount); 520 } 521 522 ImmutableSet.Builder<Object> valuesBuilder = valuesBuilder(valueComparator); 523 for (int j = 0; j < valueCount; j++) { 524 valuesBuilder.add(stream.readObject()); 525 } 526 ImmutableSet<Object> valueSet = valuesBuilder.build(); 527 if (valueSet.size() != valueCount) { 528 throw new InvalidObjectException("Duplicate key-value pairs exist for key " + key); 529 } 530 builder.put(key, valueSet); 531 tmpSize += valueCount; 532 } 533 534 ImmutableMap<Object, ImmutableSet<Object>> tmpMap; 535 try { 536 tmpMap = builder.build(); 537 } catch (IllegalArgumentException e) { 538 throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); 539 } 540 541 FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); 542 FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); 543 FieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator)); 544 } 545 546 @GwtIncompatible("not needed in emulated source.") 547 private static final long serialVersionUID = 0; 548}