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