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