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