com.google.common.collect.Maps Maven / Gradle / Ivy
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Converter;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to {@link Map} instances (including instances of {@link
* SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets}
* and {@link Queues}.
*
* See the Guava User Guide article on {@code Maps}.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Isaac Shum
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public final class Maps {
private Maps() {}
private enum EntryFunction implements Function, @Nullable Object> {
KEY {
@Override
@CheckForNull
public Object apply(Entry, ?> entry) {
return entry.getKey();
}
},
VALUE {
@Override
@CheckForNull
public Object apply(Entry, ?> entry) {
return entry.getValue();
}
};
}
@SuppressWarnings("unchecked")
static Function, K> keyFunction() {
return (Function) EntryFunction.KEY;
}
@SuppressWarnings("unchecked")
static Function, V> valueFunction() {
return (Function) EntryFunction.VALUE;
}
static Iterator keyIterator(
Iterator> entryIterator) {
return new TransformedIterator, K>(entryIterator) {
@Override
@ParametricNullness
K transform(Entry entry) {
return entry.getKey();
}
};
}
static Iterator valueIterator(
Iterator> entryIterator) {
return new TransformedIterator, V>(entryIterator) {
@Override
@ParametricNullness
V transform(Entry entry) {
return entry.getValue();
}
};
}
/**
* Returns an immutable map instance containing the given entries. Internally, the returned map
* will be backed by an {@link EnumMap}.
*
* The iteration order of the returned map follows the enum's iteration order, not the order in
* which the elements appear in the given map.
*
* @param map the map to make an immutable copy of
* @return an immutable map containing those entries
* @since 14.0
*/
@GwtCompatible(serializable = true)
public static , V> ImmutableMap immutableEnumMap(
Map map) {
if (map instanceof ImmutableEnumMap) {
@SuppressWarnings("unchecked") // safe covariant cast
ImmutableEnumMap result = (ImmutableEnumMap) map;
return result;
}
Iterator extends Entry> entryItr = map.entrySet().iterator();
if (!entryItr.hasNext()) {
return ImmutableMap.of();
}
Entry entry1 = entryItr.next();
K key1 = entry1.getKey();
V value1 = entry1.getValue();
checkEntryNotNull(key1, value1);
// Do something that works for j2cl, where we can't call getDeclaredClass():
EnumMap enumMap = new EnumMap<>(singletonMap(key1, value1));
while (entryItr.hasNext()) {
Entry entry = entryItr.next();
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
enumMap.put(key, value);
}
return ImmutableEnumMap.asImmutable(enumMap);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when
* the collection operation is performed. (This differs from the {@code Collector} returned by
* {@link java.util.stream.Collectors#toMap(java.util.function.Function,
* java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code
* IllegalStateException}.)
*
* @since 21.0
*/
public static , V>
Collector> toImmutableEnumMap(
java.util.function.Function super T, ? extends K> keyFunction,
java.util.function.Function super T, ? extends V> valueFunction) {
return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction);
}
/**
* Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
* and values are the result of applying the provided mapping functions to the input elements. The
* resulting implementation is specialized for enum key types. The returned map and its views will
* iterate over keys in their enum definition order, not encounter order.
*
* If the mapped keys contain duplicates, the values are merged using the specified merging
* function.
*
* @since 21.0
*/
public static , V>
Collector> toImmutableEnumMap(
java.util.function.Function super T, ? extends K> keyFunction,
java.util.function.Function super T, ? extends V> valueFunction,
BinaryOperator mergeFunction) {
return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction, mergeFunction);
}
/**
* Creates a mutable, empty {@code HashMap} instance.
*
* Note: if mutability is not required, use {@link ImmutableMap#of()} instead.
*
*
Note: if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashMap} constructor directly, taking advantage of "diamond" syntax.
*
* @return a new, empty {@code HashMap}
*/
public static
HashMap newHashMap() {
return new HashMap<>();
}
/**
* Creates a mutable {@code HashMap} instance with the same mappings as the specified map.
*
* Note: if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
*
Note: if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code HashMap} constructor directly, taking advantage of "diamond" syntax.
*
* @param map the mappings to be placed in the new map
* @return a new {@code HashMap} initialized with the mappings from {@code map}
*/
public static HashMap newHashMap(
Map extends K, ? extends V> map) {
return new HashMap<>(map);
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity" that it should
* hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed,
* but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method
* isn't inadvertently oversizing the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static
HashMap newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
* larger than expectedSize and the load factor is ≥ its default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
checkNonnegative(expectedSize, "expectedSize");
return expectedSize + 1;
}
if (expectedSize < Ints.MAX_POWER_OF_TWO) {
// This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap
// ends up being used to compute a "threshold" size, beyond which the internal table
// will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where
// loadFactor is 0.75 by default. So with the calculation here we ensure that the
// threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code
// path when the first operation on the new map is putAll(otherMap). There, prior to
// https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug
// meant that sometimes a too-large threshold is calculated. However, this new threshold is
// independent of the initial capacity, except that it won't be lower than the threshold
// computed from that capacity. Because the internal table is only allocated on the first
// write, we won't see copying because of the new threshold. So it is always OK to use the
// calculation here.
return (int) Math.ceil(expectedSize / 0.75);
}
return Integer.MAX_VALUE; // any large value
}
/**
* Creates a mutable, empty, insertion-ordered {@code LinkedHashMap} instance.
*
* Note: if mutability is not required, use {@link ImmutableMap#of()} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashMap} constructor directly, taking advantage of "diamond" syntax.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static
LinkedHashMap newLinkedHashMap() {
return new LinkedHashMap<>();
}
/**
* Creates a mutable, insertion-ordered {@code LinkedHashMap} instance with the same
* mappings as the specified map.
*
* Note: if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code LinkedHashMap} constructor directly, taking advantage of "diamond" syntax.
*
* @param map the mappings to be placed in the new map
* @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map}
*/
public static
LinkedHashMap newLinkedHashMap(Map extends K, ? extends V> map) {
return new LinkedHashMap<>(map);
}
/**
* Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it
* should hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently oversizing the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize}
* entries without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 19.0
*/
public static
LinkedHashMap newLinkedHashMapWithExpectedSize(int expectedSize) {
return new LinkedHashMap<>(capacity(expectedSize));
}
/**
* Creates a new empty {@link ConcurrentHashMap} instance.
*
* @since 3.0
*/
public static ConcurrentMap newConcurrentMap() {
return new ConcurrentHashMap<>();
}
/**
* Creates a mutable, empty {@code TreeMap} instance using the natural ordering of its
* elements.
*
* Note: if mutability is not required, use {@link ImmutableSortedMap#of()} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of "diamond" syntax.
*
* @return a new, empty {@code TreeMap}
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
public static TreeMap newTreeMap() {
return new TreeMap<>();
}
/**
* Creates a mutable {@code TreeMap} instance with the same mappings as the specified map
* and using the same ordering as the specified map.
*
* Note: if mutability is not required, use {@link
* ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of "diamond" syntax.
*
* @param map the sorted map whose mappings are to be placed in the new map and whose comparator
* is to be used to sort the new map
* @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the
* comparator of {@code map}
*/
public static TreeMap newTreeMap(
SortedMap map) {
return new TreeMap<>(map);
}
/**
* Creates a mutable, empty {@code TreeMap} instance using the given comparator.
*
* Note: if mutability is not required, use {@code
* ImmutableSortedMap.orderedBy(comparator).build()} instead.
*
*
Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code TreeMap} constructor directly, taking advantage of "diamond" syntax.
*
* @param comparator the comparator to sort the keys with
* @return a new, empty {@code TreeMap}
*/
public static
TreeMap newTreeMap(@CheckForNull Comparator comparator) {
// Ideally, the extra type parameter "C" shouldn't be necessary. It is a
// work-around of a compiler type inference quirk that prevents the
// following code from being compiled:
// Comparator> comparator = null;
// Map, String> map = newTreeMap(comparator);
return new TreeMap<>(comparator);
}
/**
* Creates an {@code EnumMap} instance.
*
* @param type the key type for this map
* @return a new, empty {@code EnumMap}
*/
public static , V extends @Nullable Object> EnumMap newEnumMap(
Class type) {
return new EnumMap<>(checkNotNull(type));
}
/**
* Creates an {@code EnumMap} with the same mappings as the specified map.
*
* Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code EnumMap} constructor directly, taking advantage of "diamond" syntax.
*
* @param map the map from which to initialize this {@code EnumMap}
* @return a new {@code EnumMap} initialized with the mappings from {@code map}
* @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains
* no mappings
*/
public static , V extends @Nullable Object> EnumMap newEnumMap(
Map map) {
return new EnumMap<>(map);
}
/**
* Creates an {@code IdentityHashMap} instance.
*
* Note: this method is now unnecessary and should be treated as deprecated. Instead,
* use the {@code IdentityHashMap} constructor directly, taking advantage of "diamond" syntax.
*
* @return a new, empty {@code IdentityHashMap}
*/
public static
IdentityHashMap newIdentityHashMap() {
return new IdentityHashMap<>();
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
*
Note:If you only need to know whether two maps have the same mappings, call {@code
* left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
*/
public static
MapDifference difference(
Map extends K, ? extends V> left, Map extends K, ? extends V> right) {
if (left instanceof SortedMap) {
@SuppressWarnings("unchecked")
SortedMap sortedLeft = (SortedMap) left;
return difference(sortedLeft, right);
}
return difference(left, right, Equivalence.equals());
}
/**
* Computes the difference between two maps. This difference is an immutable snapshot of the state
* of the maps at the time this method is called. It will never change, even if the maps change at
* a later time.
*
* Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
* must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @param valueEquivalence the equivalence relationship to use to compare values
* @return the difference between the two maps
* @since 10.0
*/
public static
MapDifference difference(
Map extends K, ? extends V> left,
Map extends K, ? extends V> right,
Equivalence super @NonNull V> valueEquivalence) {
Preconditions.checkNotNull(valueEquivalence);
Map onlyOnLeft = newLinkedHashMap();
Map onlyOnRight = new LinkedHashMap<>(right); // will whittle it down
Map onBoth = newLinkedHashMap();
Map> differences = newLinkedHashMap();
doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
/**
* Computes the difference between two sorted maps, using the comparator of the left map, or
* {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This
* difference is an immutable snapshot of the state of the maps at the time this method is called.
* It will never change, even if the maps change at a later time.
*
* Since this method uses {@code TreeMap} instances internally, the keys of the right map must
* all compare as distinct according to the comparator of the left map.
*
*
Note:If you only need to know whether two sorted maps have the same mappings, call
* {@code left.equals(right)} instead of this method.
*
* @param left the map to treat as the "left" map for purposes of comparison
* @param right the map to treat as the "right" map for purposes of comparison
* @return the difference between the two maps
* @since 11.0
*/
public static
SortedMapDifference difference(
SortedMap left, Map extends K, ? extends V> right) {
checkNotNull(left);
checkNotNull(right);
Comparator super K> comparator = orNaturalOrder(left.comparator());
SortedMap onlyOnLeft = Maps.newTreeMap(comparator);
SortedMap onlyOnRight = Maps.newTreeMap(comparator);
onlyOnRight.putAll(right); // will whittle it down
SortedMap onBoth = Maps.newTreeMap(comparator);
SortedMap> differences = Maps.newTreeMap(comparator);
doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
}
private static void doDifference(
Map extends K, ? extends V> left,
Map extends K, ? extends V> right,
Equivalence super @NonNull V> valueEquivalence,
Map onlyOnLeft,
Map onlyOnRight,
Map onBoth,
Map> differences) {
for (Entry extends K, ? extends V> entry : left.entrySet()) {
K leftKey = entry.getKey();
V leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
/*
* The cast is safe because onlyOnRight contains all the keys of right.
*
* TODO(cpovirk): Consider checking onlyOnRight.containsKey instead of right.containsKey.
* That could change behavior if the input maps use different equivalence relations (and so
* a key that appears once in `right` might appear multiple times in `left`). We don't
* guarantee behavior in that case, anyway, and the current behavior is likely undesirable.
* So that's either a reason to feel free to change it or a reason to not bother thinking
* further about this.
*/
V rightValue = uncheckedCastNullableTToT(onlyOnRight.remove(leftKey));
if (valueEquivalence.equivalent(leftValue, rightValue)) {
onBoth.put(leftKey, leftValue);
} else {
differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
}
private static Map unmodifiableMap(
Map map) {
if (map instanceof SortedMap) {
return Collections.unmodifiableSortedMap((SortedMap) map);
} else {
return Collections.unmodifiableMap(map);
}
}
static class MapDifferenceImpl
implements MapDifference {
final Map onlyOnLeft;
final Map onlyOnRight;
final Map onBoth;
final Map> differences;
MapDifferenceImpl(
Map onlyOnLeft,
Map onlyOnRight,
Map onBoth,
Map> differences) {
this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
this.onlyOnRight = unmodifiableMap(onlyOnRight);
this.onBoth = unmodifiableMap(onBoth);
this.differences = unmodifiableMap(differences);
}
@Override
public boolean areEqual() {
return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
}
@Override
public Map entriesOnlyOnLeft() {
return onlyOnLeft;
}
@Override
public Map entriesOnlyOnRight() {
return onlyOnRight;
}
@Override
public Map entriesInCommon() {
return onBoth;
}
@Override
public Map> entriesDiffering() {
return differences;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object == this) {
return true;
}
if (object instanceof MapDifference) {
MapDifference, ?> other = (MapDifference, ?>) object;
return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
&& entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
&& entriesInCommon().equals(other.entriesInCommon())
&& entriesDiffering().equals(other.entriesDiffering());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(
entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering());
}
@Override
public String toString() {
if (areEqual()) {
return "equal";
}
StringBuilder result = new StringBuilder("not equal");
if (!onlyOnLeft.isEmpty()) {
result.append(": only on left=").append(onlyOnLeft);
}
if (!onlyOnRight.isEmpty()) {
result.append(": only on right=").append(onlyOnRight);
}
if (!differences.isEmpty()) {
result.append(": value differences=").append(differences);
}
return result.toString();
}
}
static class ValueDifferenceImpl
implements MapDifference.ValueDifference {
@ParametricNullness private final V left;
@ParametricNullness private final V right;
static ValueDifference create(
@ParametricNullness V left, @ParametricNullness V right) {
return new ValueDifferenceImpl<>(left, right);
}
private ValueDifferenceImpl(@ParametricNullness V left, @ParametricNullness V right) {
this.left = left;
this.right = right;
}
@Override
@ParametricNullness
public V leftValue() {
return left;
}
@Override
@ParametricNullness
public V rightValue() {
return right;
}
@Override
public boolean equals(@CheckForNull Object object) {
if (object instanceof MapDifference.ValueDifference) {
MapDifference.ValueDifference> that = (MapDifference.ValueDifference>) object;
return Objects.equal(this.left, that.leftValue())
&& Objects.equal(this.right, that.rightValue());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(left, right);
}
@Override
public String toString() {
return "(" + left + ", " + right + ")";
}
}
static class SortedMapDifferenceImpl
extends MapDifferenceImpl implements SortedMapDifference {
SortedMapDifferenceImpl(
SortedMap onlyOnLeft,
SortedMap onlyOnRight,
SortedMap onBoth,
SortedMap> differences) {
super(onlyOnLeft, onlyOnRight, onBoth, differences);
}
@Override
public SortedMap> entriesDiffering() {
return (SortedMap>) super.entriesDiffering();
}
@Override
public SortedMap entriesInCommon() {
return (SortedMap) super.entriesInCommon();
}
@Override
public SortedMap entriesOnlyOnLeft() {
return (SortedMap) super.entriesOnlyOnLeft();
}
@Override
public SortedMap entriesOnlyOnRight() {
return (SortedMap) super.entriesOnlyOnRight();
}
}
/**
* Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}.
* This method is an abomination of generics; the only purpose of this method is to contain the
* ugly type-casting in one place.
*/
@SuppressWarnings("unchecked")
static Comparator super E> orNaturalOrder(
@CheckForNull Comparator super E> comparator) {
if (comparator != null) { // can't use ? : because of javac bug 5080917
return comparator;
}
return (Comparator) Ordering.natural();
}
/**
* Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are
* computed on demand using {@code function}. To get an immutable copy instead, use {@link
* #toMap(Iterable, Function)}.
*
* Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
*
Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
*
Warning: If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
*
Warning: This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static Map asMap(
Set set, Function super K, V> function) {
return new AsMapView<>(set, function);
}
/**
* Returns a view of the sorted set as a map, mapping keys from the set according to the specified
* function.
*
* Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
*
Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
*
Warning: If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
*
Warning: This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
public static SortedMap asMap(
SortedSet set, Function super K, V> function) {
return new SortedAsMapView<>(set, function);
}
/**
* Returns a view of the navigable set as a map, mapping keys from the set according to the
* specified function.
*
* Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
* {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
* entrySet} views of the returned map iterate in the same order as the backing set.
*
*
Modifications to the backing set are read through to the returned map. The returned map
* supports removal operations if the backing set does. Removal operations write through to the
* backing set. The returned map does not support put operations.
*
*
Warning: If the function rejects {@code null}, caution is required to make sure the
* set does not contain {@code null}, because the view cannot stop {@code null} from being added
* to the set.
*
*
Warning: This method assumes that for any instance {@code k} of key type {@code K},
* {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
* which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
* calling methods on the resulting map view.
*
* @since 14.0
*/
@GwtIncompatible // NavigableMap
public static NavigableMap asMap(
NavigableSet set, Function super K, V> function) {
return new NavigableAsMapView<>(set, function);
}
private static class AsMapView
extends ViewCachingAbstractMap {
private final Set set;
final Function super K, V> function;
Set backingSet() {
return set;
}
AsMapView(Set set, Function super K, V> function) {
this.set = checkNotNull(set);
this.function = checkNotNull(function);
}
@Override
public Set createKeySet() {
return removeOnlySet(backingSet());
}
@Override
Collection createValues() {
return Collections2.transform(set, function);
}
@Override
public int size() {
return backingSet().size();
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return backingSet().contains(key);
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return getOrDefault(key, null);
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
if (Collections2.safeContains(backingSet(), key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
if (backingSet().remove(key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return null;
}
}
@Override
public void clear() {
backingSet().clear();
}
@Override
protected Set> createEntrySet() {
@WeakOuter
class EntrySetImpl extends EntrySet {
@Override
Map map() {
return AsMapView.this;
}
@Override
public Iterator> iterator() {
return asMapEntryIterator(backingSet(), function);
}
}
return new EntrySetImpl();
}
@Override
public void forEach(BiConsumer super K, ? super V> action) {
checkNotNull(action);
// avoids allocation of entries
backingSet().forEach(k -> action.accept(k, function.apply(k)));
}
}
static
Iterator> asMapEntryIterator(Set set, final Function super K, V> function) {
return new TransformedIterator>(set.iterator()) {
@Override
Entry transform(@ParametricNullness final K key) {
return immutableEntry(key, function.apply(key));
}
};
}
private static class SortedAsMapView
extends AsMapView implements SortedMap {
SortedAsMapView(SortedSet set, Function super K, V> function) {
super(set, function);
}
@Override
SortedSet backingSet() {
return (SortedSet) super.backingSet();
}
@Override
@CheckForNull
public Comparator super K> comparator() {
return backingSet().comparator();
}
@Override
public Set keySet() {
return removeOnlySortedSet(backingSet());
}
@Override
public SortedMap subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
return asMap(backingSet().subSet(fromKey, toKey), function);
}
@Override
public SortedMap headMap(@ParametricNullness K toKey) {
return asMap(backingSet().headSet(toKey), function);
}
@Override
public SortedMap tailMap(@ParametricNullness K fromKey) {
return asMap(backingSet().tailSet(fromKey), function);
}
@Override
@ParametricNullness
public K firstKey() {
return backingSet().first();
}
@Override
@ParametricNullness
public K lastKey() {
return backingSet().last();
}
}
@GwtIncompatible // NavigableMap
private static final class NavigableAsMapView<
K extends @Nullable Object, V extends @Nullable Object>
extends AbstractNavigableMap {
/*
* Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
* NavigableMap methods.
*/
private final NavigableSet set;
private final Function super K, V> function;
NavigableAsMapView(NavigableSet ks, Function super K, V> vFunction) {
this.set = checkNotNull(ks);
this.function = checkNotNull(vFunction);
}
@Override
public NavigableMap subMap(
@ParametricNullness K fromKey,
boolean fromInclusive,
@ParametricNullness K toKey,
boolean toInclusive) {
return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function);
}
@Override
public NavigableMap headMap(@ParametricNullness K toKey, boolean inclusive) {
return asMap(set.headSet(toKey, inclusive), function);
}
@Override
public NavigableMap tailMap(@ParametricNullness K fromKey, boolean inclusive) {
return asMap(set.tailSet(fromKey, inclusive), function);
}
@Override
@CheckForNull
public Comparator super K> comparator() {
return set.comparator();
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return getOrDefault(key, null);
}
@Override
@CheckForNull
public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
if (Collections2.safeContains(set, key)) {
@SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
K k = (K) key;
return function.apply(k);
} else {
return defaultValue;
}
}
@Override
public void clear() {
set.clear();
}
@Override
Iterator> entryIterator() {
return asMapEntryIterator(set, function);
}
@Override
Spliterator> entrySpliterator() {
return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e)));
}
@Override
public void forEach(BiConsumer super K, ? super V> action) {
set.forEach(k -> action.accept(k, function.apply(k)));
}
@Override
Iterator> descendingEntryIterator() {
return descendingMap().entrySet().iterator();
}
@Override
public NavigableSet navigableKeySet() {
return removeOnlyNavigableSet(set);
}
@Override
public int size() {
return set.size();
}
@Override
public NavigableMap descendingMap() {
return asMap(set.descendingSet(), function);
}
}
private static Set removeOnlySet(final Set set) {
return new ForwardingSet() {
@Override
protected Set delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection extends E> es) {
throw new UnsupportedOperationException();
}
};
}
private static SortedSet removeOnlySortedSet(
final SortedSet set) {
return new ForwardingSortedSet() {
@Override
protected SortedSet delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet headSet(@ParametricNullness E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public SortedSet subSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public SortedSet tailSet(@ParametricNullness E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
};
}
@GwtIncompatible // NavigableSet
private static NavigableSet removeOnlyNavigableSet(
final NavigableSet set) {
return new ForwardingNavigableSet() {
@Override
protected NavigableSet delegate() {
return set;
}
@Override
public boolean add(@ParametricNullness E element) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection extends E> es) {
throw new UnsupportedOperationException();
}
@Override
public SortedSet headSet(@ParametricNullness E toElement) {
return removeOnlySortedSet(super.headSet(toElement));
}
@Override
public NavigableSet headSet(@ParametricNullness E toElement, boolean inclusive) {
return removeOnlyNavigableSet(super.headSet(toElement, inclusive));
}
@Override
public SortedSet subSet(
@ParametricNullness E fromElement, @ParametricNullness E toElement) {
return removeOnlySortedSet(super.subSet(fromElement, toElement));
}
@Override
public NavigableSet subSet(
@ParametricNullness E fromElement,
boolean fromInclusive,
@ParametricNullness E toElement,
boolean toInclusive) {
return removeOnlyNavigableSet(
super.subSet(fromElement, fromInclusive, toElement, toInclusive));
}
@Override
public SortedSet tailSet(@ParametricNullness E fromElement) {
return removeOnlySortedSet(super.tailSet(fromElement));
}
@Override
public NavigableSet tailSet(@ParametricNullness E fromElement, boolean inclusive) {
return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive));
}
@Override
public NavigableSet descendingSet() {
return removeOnlyNavigableSet(super.descendingSet());
}
};
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
*
If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link
* Maps#asMap(Set, Function)}.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static ImmutableMap toMap(
Iterable keys, Function super K, V> valueFunction) {
return toMap(keys.iterator(), valueFunction);
}
/**
* Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
* for each key was computed by {@code valueFunction}. The map's iteration order is the order of
* the first appearance of each key in {@code keys}.
*
* When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
* valueFunction} will be applied to more than one instance of that key and, if it is, which
* result will be mapped to that key in the returned map.
*
* @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
* valueFunction} produces {@code null} for any key
* @since 14.0
*/
public static ImmutableMap toMap(
Iterator keys, Function super K, V> valueFunction) {
checkNotNull(valueFunction);
ImmutableMap.Builder builder = ImmutableMap.builder();
while (keys.hasNext()) {
K key = keys.next();
builder.put(key, valueFunction.apply(key));
}
// Using buildKeepingLast() so as not to fail on duplicate keys
return builder.buildKeepingLast();
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* {@code
* Color red = new Color("red", 255, 0, 0);
* ...
* ImmutableSet allColors = ImmutableSet.of(red, green, blue);
*
* ImmutableMap colorForName =
* uniqueIndex(allColors, c -> c.toString());
* assertThat(colorForName).containsEntry("red", red);
* }
*
* If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterable, Function) Multimaps.index}.
*
*
Note: on Java 8+, it is usually better to use streams. For example:
*
*
{@code
* import static com.google.common.collect.ImmutableMap.toImmutableMap;
* ...
* ImmutableMap colorForName =
* allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
* }
*
* Streams provide a more standard and flexible API and the lambdas make it clear what the keys
* and values in the map are.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
*/
@CanIgnoreReturnValue
public static ImmutableMap uniqueIndex(
Iterable values, Function super V, K> keyFunction) {
if (values instanceof Collection) {
return uniqueIndex(
values.iterator(),
keyFunction,
ImmutableMap.builderWithExpectedSize(((Collection>) values).size()));
}
return uniqueIndex(values.iterator(), keyFunction);
}
/**
* Returns a map with the given {@code values}, indexed by keys derived from those values. In
* other words, each input value produces an entry in the map whose key is the result of applying
* {@code keyFunction} to that value. These entries appear in the same order as the input values.
* Example usage:
*
* {@code
* Color red = new Color("red", 255, 0, 0);
* ...
* Iterator allColors = ImmutableSet.of(red, green, blue).iterator();
*
* Map colorForName =
* uniqueIndex(allColors, toStringFunction());
* assertThat(colorForName).containsEntry("red", red);
* }
*
* If your index may associate multiple values with each key, use {@link
* Multimaps#index(Iterator, Function) Multimaps.index}.
*
* @param values the values to use when constructing the {@code Map}
* @param keyFunction the function used to produce the key for each value
* @return a map mapping the result of evaluating the function {@code keyFunction} on each value
* in the input collection to that value
* @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
* value in the input collection
* @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
* keyFunction} produces {@code null} for any value
* @since 10.0
*/
@CanIgnoreReturnValue
public static ImmutableMap uniqueIndex(
Iterator values, Function super V, K> keyFunction) {
return uniqueIndex(values, keyFunction, ImmutableMap.builder());
}
private static ImmutableMap uniqueIndex(
Iterator values, Function super V, K> keyFunction, ImmutableMap.Builder builder) {
checkNotNull(keyFunction);
while (values.hasNext()) {
V value = values.next();
builder.put(keyFunction.apply(value), value);
}
try {
return builder.buildOrThrow();
} catch (IllegalArgumentException duplicateKeys) {
throw new IllegalArgumentException(
duplicateKeys.getMessage()
+ ". To index multiple values under a key, use Multimaps.index.");
}
}
/**
* Creates an {@code ImmutableMap} from a {@code Properties} instance. Properties
* normally derive from {@code Map