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