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; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtCompatible; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import java.util.Arrays; 025import java.util.Comparator; 026import java.util.Map; 027import java.util.function.Function; 028import java.util.stream.Collector; 029import java.util.stream.Collectors; 030 031/** 032 * A {@link BiMap} whose contents will never change, with many other important properties detailed 033 * at {@link ImmutableCollection}. 034 * 035 * @author Jared Levy 036 * @since 2.0 037 */ 038@GwtCompatible(serializable = true, emulated = true) 039public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<K, V> 040 implements BiMap<K, V> { 041 042 /** 043 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableBiMap} whose 044 * keys and values are the result of applying the provided mapping functions to the input 045 * elements. Entries appear in the result {@code ImmutableBiMap} in encounter order. 046 * 047 * <p>If the mapped keys or values contain duplicates 048 * (according to {@link Object#equals(Object)}, an {@code IllegalArgumentException} is thrown 049 * when the collection operation is performed. (This differs from the {@code Collector} returned 050 * by {@link Collectors#toMap(Function, Function)}, which throws an 051 * {@code IllegalStateException}.) 052 * 053 * @since 21.0 054 */ 055 @Beta 056 public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap( 057 Function<? super T, ? extends K> keyFunction, 058 Function<? super T, ? extends V> valueFunction) { 059 return CollectCollectors.toImmutableBiMap(keyFunction, valueFunction); 060 } 061 062 /** 063 * Returns the empty bimap. 064 */ 065 // Casting to any type is safe because the set will never hold any elements. 066 @SuppressWarnings("unchecked") 067 public static <K, V> ImmutableBiMap<K, V> of() { 068 return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY; 069 } 070 071 /** 072 * Returns an immutable bimap containing a single entry. 073 */ 074 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { 075 return new SingletonImmutableBiMap<>(k1, v1); 076 } 077 078 /** 079 * Returns an immutable map containing the given entries, in order. 080 * 081 * @throws IllegalArgumentException if duplicate keys or values are added 082 */ 083 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { 084 return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2)); 085 } 086 087 /** 088 * Returns an immutable map containing the given entries, in order. 089 * 090 * @throws IllegalArgumentException if duplicate keys or values are added 091 */ 092 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 093 return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); 094 } 095 096 /** 097 * Returns an immutable map containing the given entries, in order. 098 * 099 * @throws IllegalArgumentException if duplicate keys or values are added 100 */ 101 public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 102 return RegularImmutableBiMap.fromEntries( 103 entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); 104 } 105 106 /** 107 * Returns an immutable map containing the given entries, in order. 108 * 109 * @throws IllegalArgumentException if duplicate keys or values are added 110 */ 111 public static <K, V> ImmutableBiMap<K, V> of( 112 K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 113 return RegularImmutableBiMap.fromEntries( 114 entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); 115 } 116 117 // looking for of() with > 5 entries? Use the builder instead. 118 119 /** 120 * Returns a new builder. The generated builder is equivalent to the builder 121 * created by the {@link Builder} constructor. 122 */ 123 public static <K, V> Builder<K, V> builder() { 124 return new Builder<>(); 125 } 126 127 /** 128 * Returns a new builder, expecting the specified number of entries to be added. 129 * 130 * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link 131 * Builder#build} is called, the builder is likely to perform better than an unsized {@link 132 * #builder()} would have. 133 * 134 * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, 135 * but not exactly, the number of entries added to the builder. 136 * 137 * @since 23.1 138 */ 139 @Beta 140 public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) { 141 checkNonnegative(expectedSize, "expectedSize"); 142 return new Builder<>(expectedSize); 143 } 144 145 /** 146 * A builder for creating immutable bimap instances, especially {@code public 147 * static final} bimaps ("constant bimaps"). Example: <pre> {@code 148 * 149 * static final ImmutableBiMap<String, Integer> WORD_TO_INT = 150 * new ImmutableBiMap.Builder<String, Integer>() 151 * .put("one", 1) 152 * .put("two", 2) 153 * .put("three", 3) 154 * .build();}</pre> 155 * 156 * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods 157 * are even more convenient. 158 * 159 * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order 160 * they were inserted into the builder. For example, in the above example, 161 * {@code WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order 162 * {@code "one"=1, "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same 163 * order. If you want a different order, consider using 164 * {@link #orderEntriesByValue(Comparator)}, which changes this builder to sort 165 * entries by value. 166 * 167 * <p>Builder instances can be reused - it is safe to call {@link #build} 168 * multiple times to build multiple bimaps in series. Each bimap is a superset 169 * of the bimaps created before it. 170 * 171 * @since 2.0 172 */ 173 public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { 174 175 /** 176 * Creates a new builder. The returned builder is equivalent to the builder 177 * generated by {@link ImmutableBiMap#builder}. 178 */ 179 public Builder() {} 180 181 Builder(int size) { 182 super(size); 183 } 184 185 /** 186 * Associates {@code key} with {@code value} in the built bimap. Duplicate 187 * keys or values are not allowed, and will cause {@link #build} to fail. 188 */ 189 @CanIgnoreReturnValue 190 @Override 191 public Builder<K, V> put(K key, V value) { 192 super.put(key, value); 193 return this; 194 } 195 196 /** 197 * Adds the given {@code entry} to the bimap. Duplicate keys or values 198 * are not allowed, and will cause {@link #build} to fail. 199 * 200 * @since 19.0 201 */ 202 @CanIgnoreReturnValue 203 @Override 204 public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 205 super.put(entry); 206 return this; 207 } 208 209 /** 210 * Associates all of the given map's keys and values in the built bimap. 211 * Duplicate keys or values are not allowed, and will cause {@link #build} 212 * to fail. 213 * 214 * @throws NullPointerException if any key or value in {@code map} is null 215 */ 216 @CanIgnoreReturnValue 217 @Override 218 public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { 219 super.putAll(map); 220 return this; 221 } 222 223 /** 224 * Adds all of the given entries to the built bimap. Duplicate keys or 225 * values are not allowed, and will cause {@link #build} to fail. 226 * 227 * @throws NullPointerException if any key, value, or entry is null 228 * @since 19.0 229 */ 230 @CanIgnoreReturnValue 231 @Beta 232 @Override 233 public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 234 super.putAll(entries); 235 return this; 236 } 237 238 /** 239 * Configures this {@code Builder} to order entries by value according to the specified 240 * comparator. 241 * 242 * <p>The sort order is stable, that is, if two entries have values that compare 243 * as equivalent, the entry that was inserted first will be first in the built map's 244 * iteration order. 245 * 246 * @throws IllegalStateException if this method was already called 247 * @since 19.0 248 */ 249 @CanIgnoreReturnValue 250 @Beta 251 @Override 252 public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { 253 super.orderEntriesByValue(valueComparator); 254 return this; 255 } 256 257 @Override 258 @CanIgnoreReturnValue 259 Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) { 260 super.combine(builder); 261 return this; 262 } 263 264 /** 265 * Returns a newly-created immutable bimap. The iteration order of the returned bimap is 266 * the order in which entries were inserted into the builder, unless 267 * {@link #orderEntriesByValue} was called, in which case entries are sorted by value. 268 * 269 * @throws IllegalArgumentException if duplicate keys or values were added 270 */ 271 @Override 272 public ImmutableBiMap<K, V> build() { 273 switch (size) { 274 case 0: 275 return of(); 276 case 1: 277 return of(entries[0].getKey(), entries[0].getValue()); 278 default: 279 /* 280 * If entries is full, then this implementation may end up using the entries array 281 * directly and writing over the entry objects with non-terminal entries, but this is 282 * safe; if this Builder is used further, it will grow the entries array (so it can't 283 * affect the original array), and future build() calls will always copy any entry 284 * objects that cannot be safely reused. 285 */ 286 if (valueComparator != null) { 287 if (entriesUsed) { 288 entries = Arrays.copyOf(entries, size); 289 } 290 Arrays.sort( 291 entries, 292 0, 293 size, 294 Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction())); 295 } 296 entriesUsed = size == entries.length; 297 return RegularImmutableBiMap.fromEntryArray(size, entries); 298 } 299 } 300 } 301 302 /** 303 * Returns an immutable bimap containing the same entries as {@code map}. If 304 * {@code map} somehow contains entries with duplicate keys (for example, if 305 * it is a {@code SortedMap} whose comparator is not <i>consistent with 306 * equals</i>), the results of this method are undefined. 307 * 308 * <p>The returned {@code BiMap} iterates over entries in the same order as the 309 * {@code entrySet} of the original map. 310 * 311 * <p>Despite the method name, this method attempts to avoid actually copying 312 * the data when it is safe to do so. The exact circumstances under which a 313 * copy will or will not be performed are undocumented and subject to change. 314 * 315 * @throws IllegalArgumentException if two keys have the same value or two values have the same 316 * key 317 * @throws NullPointerException if any key or value in {@code map} is null 318 */ 319 public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) { 320 if (map instanceof ImmutableBiMap) { 321 @SuppressWarnings("unchecked") // safe since map is not writable 322 ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; 323 // TODO(lowasser): if we need to make a copy of a BiMap because the 324 // forward map is a view, don't make a copy of the non-view delegate map 325 if (!bimap.isPartialView()) { 326 return bimap; 327 } 328 } 329 return copyOf(map.entrySet()); 330 } 331 332 /** 333 * Returns an immutable bimap containing the given entries. The returned bimap iterates over 334 * entries in the same order as the original iterable. 335 * 336 * @throws IllegalArgumentException if two keys have the same value or two 337 * values have the same key 338 * @throws NullPointerException if any key, value, or entry is null 339 * @since 19.0 340 */ 341 @Beta 342 public static <K, V> ImmutableBiMap<K, V> copyOf( 343 Iterable<? extends Entry<? extends K, ? extends V>> entries) { 344 @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant 345 Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY); 346 switch (entryArray.length) { 347 case 0: 348 return of(); 349 case 1: 350 Entry<K, V> entry = entryArray[0]; 351 return of(entry.getKey(), entry.getValue()); 352 default: 353 /* 354 * The current implementation will end up using entryArray directly, though it will write 355 * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray. 356 */ 357 return RegularImmutableBiMap.fromEntries(entryArray); 358 } 359 } 360 361 ImmutableBiMap() {} 362 363 /** 364 * {@inheritDoc} 365 * 366 * <p>The inverse of an {@code ImmutableBiMap} is another 367 * {@code ImmutableBiMap}. 368 */ 369 @Override 370 public abstract ImmutableBiMap<V, K> inverse(); 371 372 /** 373 * Returns an immutable set of the values in this map, in the same order they appear in {@link 374 * #entrySet}. 375 */ 376 @Override 377 public ImmutableSet<V> values() { 378 return inverse().keySet(); 379 } 380 381 @Override 382 final ImmutableSet<V> createValues() { 383 throw new AssertionError("should never be called"); 384 } 385 386 /** 387 * Guaranteed to throw an exception and leave the bimap unmodified. 388 * 389 * @throws UnsupportedOperationException always 390 * @deprecated Unsupported operation. 391 */ 392 @CanIgnoreReturnValue 393 @Deprecated 394 @Override 395 public V forcePut(K key, V value) { 396 throw new UnsupportedOperationException(); 397 } 398 399 /** 400 * Serialized type for all ImmutableBiMap instances. It captures the logical 401 * contents and they are reconstructed using public factory methods. This 402 * ensures that the implementation types remain as implementation details. 403 * 404 * Since the bimap is immutable, ImmutableBiMap doesn't require special logic 405 * for keeping the bimap and its inverse in sync during serialization, the way 406 * AbstractBiMap does. 407 */ 408 private static class SerializedForm extends ImmutableMap.SerializedForm { 409 SerializedForm(ImmutableBiMap<?, ?> bimap) { 410 super(bimap); 411 } 412 413 @Override 414 Object readResolve() { 415 Builder<Object, Object> builder = new Builder<>(); 416 return createMap(builder); 417 } 418 419 private static final long serialVersionUID = 0; 420 } 421 422 @Override 423 Object writeReplace() { 424 return new SerializedForm(this); 425 } 426}