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