Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * 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.base.Predicates.equalTo;
  import static com.google.common.base.Predicates.in;
  import static com.google.common.base.Predicates.not;
  
  
  import java.util.EnumMap;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.Set;
  import java.util.TreeMap;
  
  import  javax.annotation.Nullable;

Static utility methods pertaining to Map instances (including instances of SortedMap, BiMap, etc.). Also see this class's counterparts Lists, Sets and Queues.

See the Guava User Guide article on Maps.

Author(s):
Kevin Bourrillion
Mike Bostock
Isaac Shum
Louis Wasserman
Since:
2.0 (imported from Google Collections Library)
  
  @GwtCompatible(emulated = true)
  public final class Maps {
    private Maps() {}
  
    private enum EntryFunction implements Function<Entry<?, ?>, Object> {
      KEY {
        @Override
        @Nullable
        public Object apply(Entry<?, ?> entry) {
          return entry.getKey();
        }
      },
      VALUE {
        @Override
        @Nullable
        public Object apply(Entry<?, ?> entry) {
          return entry.getValue();
        }
      };
    }
  
   @SuppressWarnings("unchecked")
   static <K> Function<Entry<K, ?>, K> keyFunction() {
     return (Function.;
   }
 
   @SuppressWarnings("unchecked")
   static <V> Function<Entry<?, V>, V> valueFunction() {
     return (Function.;
   }
 
   static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) {
     return Iterators.transform(entryIterator, Maps.<K>keyFunction());
   }
 
   static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) {
     return Iterators.transform(entryIterator, Maps.<V>valueFunction());
   }
 
   static <K, V> UnmodifiableIterator<V> valueIterator(
       final UnmodifiableIterator<Entry<K, V>> entryIterator) {
     return new UnmodifiableIterator<V>() {
       @Override
       public boolean hasNext() {
         return entryIterator.hasNext();
       }
 
       @Override
       public V next() {
         return entryIterator.next().getValue();
       }
     };
   }

  
Returns an immutable map instance containing the given entries. Internally, the returned map will be backed by an 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.

Parameters:
map the map to make an immutable copy of
Returns:
an immutable map containing those entries
Since:
14.0
 
   @GwtCompatible(serializable = true)
   @Beta
   public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
       Map<K, ? extends V> map) {
     if (map instanceof ImmutableEnumMap) {
       @SuppressWarnings("unchecked"// safe covariant cast
       ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
       return result;
     } else if (map.isEmpty()) {
       return ImmutableMap.of();
     } else {
       for (Map.Entry<K, ? extends V> entry : map.entrySet()) {
         checkNotNull(entry.getKey());
         checkNotNull(entry.getValue());
       }
       return ImmutableEnumMap.asImmutable(new EnumMap<K, V>(map));
     }
   }

  
Creates a mutable, empty HashMap instance.

Note: if mutability is not required, use ImmutableMap.of() instead.

Note: if K is an enum type, use newEnumMap instead.

Returns:
a new, empty HashMap
 
   public static <K, V> HashMap<K, V> newHashMap() {
     return new HashMap<K, V>();
   }

  
Creates a HashMap instance, with a high enough "initial capacity" that it should hold expectedSize elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.

Parameters:
expectedSize the number of elements you expect to add to the returned map
Returns:
a new, empty HashMap with enough capacity to hold expectedSize elements without resizing
Throws:
IllegalArgumentException if expectedSize is negative
 
   public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
       int expectedSize) {
     return new HashMap<K, V>(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) {
       checkArgument(expectedSize >= 0);
       return expectedSize + 1;
     }
     if (expectedSize < .) {
       return expectedSize + expectedSize / 3;
     }
     return .// any large value
   }

  
Creates a mutable HashMap instance with the same mappings as the specified map.

Note: if mutability is not required, use ImmutableMap.copyOf(Map) instead.

Note: if K is an Enum type, use newEnumMap instead.

Parameters:
map the mappings to be placed in the new map
Returns:
a new HashMap initialized with the mappings from map
 
   public static <K, V> HashMap<K, V> newHashMap(
       Map<? extends K, ? extends V> map) {
     return new HashMap<K, V>(map);
   }

  
Creates a mutable, empty, insertion-ordered LinkedHashMap instance.

Note: if mutability is not required, use ImmutableMap.of() instead.

Returns:
a new, empty LinkedHashMap
 
   public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
     return new LinkedHashMap<K, V>();
   }

  
Creates a mutable, insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Note: if mutability is not required, use ImmutableMap.copyOf(Map) instead.

Parameters:
map the mappings to be placed in the new map
Returns:
a new, LinkedHashMap initialized with the mappings from map
 
   public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(
       Map<? extends K, ? extends V> map) {
     return new LinkedHashMap<K, V>(map);
   }

  
Returns a general-purpose instance of ConcurrentMap, which supports all optional operations of the ConcurrentMap interface. It does not permit null keys or values. It is serializable.

This is currently accomplished by calling MapMaker.makeMap().

It is preferable to use MapMaker directly (rather than through this method), as it presents numerous useful configuration options, such as the concurrency level, load factor, key/value reference types, and value computation.

Returns:
a new, empty ConcurrentMap
Since:
3.0
 
   public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
     return new MapMaker().<K, V>makeMap();
   }

  
Creates a mutable, empty TreeMap instance using the natural ordering of its elements.

Note: if mutability is not required, use ImmutableSortedMap.of() instead.

Returns:
a new, empty TreeMap
 
   public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
     return new TreeMap<K, V>();
   }

  
Creates a mutable 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 ImmutableSortedMap.copyOfSorted(SortedMap) instead.

Parameters:
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
Returns:
a new TreeMap initialized with the mappings from map and using the comparator of map
 
   public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
     return new TreeMap<K, V>(map);
   }

  
Creates a mutable, empty TreeMap instance using the given comparator.

Note: if mutability is not required, use ImmutableSortedMap.orderedBy(comparator).build() instead.

Parameters:
comparator the comparator to sort the keys with
Returns:
a new, empty TreeMap
 
   public static <C, K extends C, V> TreeMap<K, V> newTreeMap(
       @Nullable Comparator<C> 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<Class<?>> comparator = null;
     // Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
     return new TreeMap<K, V>(comparator);
   }

  
Creates an EnumMap instance.

Parameters:
type the key type for this map
Returns:
a new, empty EnumMap
 
   public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
     return new EnumMap<K, V>(checkNotNull(type));
   }

  
Creates an EnumMap with the same mappings as the specified map.

Parameters:
map the map from which to initialize this EnumMap
Returns:
a new EnumMap initialized with the mappings from map
Throws:
IllegalArgumentException if m is not an EnumMap instance and contains no mappings
 
   public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(
       Map<K, ? extends V> map) {
     return new EnumMap<K, V>(map);
   }

  
Creates an IdentityHashMap instance.

Returns:
a new, empty IdentityHashMap
 
   public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
     return new IdentityHashMap<K, V>();
   }

  
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 HashMap instances internally, the keys of the supplied maps must be well-behaved with respect to Object.equals and Object.hashCode.

Note:If you only need to know whether two maps have the same mappings, call left.equals(right) instead of this method.

Parameters:
left the map to treat as the "left" map for purposes of comparison
right the map to treat as the "right" map for purposes of comparison
Returns:
the difference between the two maps
 
   @SuppressWarnings("unchecked")
   public static <K, V> MapDifference<K, V> difference(
       Map<? extends K, ? extends V> leftMap<? extends K, ? extends V> right) {
     if (left instanceof SortedMap) {
       SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
       SortedMapDifference<K, V> result = difference(sortedLeftright);
       return result;
     }
     return difference(leftright, 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.

Values are compared using a provided equivalence, in the case of equality, the value on the 'left' is returned in the difference.

Since this method uses HashMap instances internally, the keys of the supplied maps must be well-behaved with respect to Object.equals and Object.hashCode.

Parameters:
left the map to treat as the "left" map for purposes of comparison
right the map to treat as the "right" map for purposes of comparison
valueEquivalence the equivalence relationship to use to compare values
Returns:
the difference between the two maps
Since:
10.0
 
   @Beta
   public static <K, V> MapDifference<K, V> difference(
       Map<? extends K, ? extends V> leftMap<? extends K, ? extends V> right,
       Equivalence<? super V> valueEquivalence) {
     Preconditions.checkNotNull(valueEquivalence);
 
     Map<K, V> onlyOnLeft = newHashMap();
     Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down
     Map<K, V> onBoth = newHashMap();
     Map<K, MapDifference.ValueDifference<V>> differences = newHashMap();
     doDifference(leftrightvalueEquivalenceonlyOnLeftonlyOnRightonBothdifferences);
     return new MapDifferenceImpl<K, V>(onlyOnLeftonlyOnRightonBothdifferences);
   }
 
   private static <K, V> void doDifference(
       Map<? extends K, ? extends V> leftMap<? extends K, ? extends V> right,
       Equivalence<? super V> valueEquivalence,
       Map<K, V> onlyOnLeftMap<K, V> onlyOnRightMap<K, V> onBoth,
       Map<K, MapDifference.ValueDifference<V>> differences) {
     for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
       K leftKey = entry.getKey();
       V leftValue = entry.getValue();
       if (right.containsKey(leftKey)) {
         V rightValue = onlyOnRight.remove(leftKey);
         if (valueEquivalence.equivalent(leftValuerightValue)) {
           onBoth.put(leftKeyleftValue);
         } else {
           differences.put(
               leftKey, ValueDifferenceImpl.create(leftValuerightValue));
         }
       } else {
         onlyOnLeft.put(leftKeyleftValue);
       }
     }
   }
 
   private static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
     if (map instanceof SortedMap) {
       return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
     } else {
       return Collections.unmodifiableMap(map);
     }
   }
 
   static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
     final Map<K, V> onlyOnLeft;
     final Map<K, V> onlyOnRight;
     final Map<K, V> onBoth;
     final Map<K, ValueDifference<V>> differences;
 
     MapDifferenceImpl(Map<K, V> onlyOnLeft,
         Map<K, V> onlyOnRightMap<K, V> onBoth,
         Map<K, ValueDifference<V>> differences) {
       this. = unmodifiableMap(onlyOnLeft);
       this. = unmodifiableMap(onlyOnRight);
       this. = unmodifiableMap(onBoth);
       this. = unmodifiableMap(differences);
     }
 
     @Override
     public boolean areEqual() {
       return .isEmpty() && .isEmpty() && .isEmpty();
     }
 
     @Override
     public Map<K, V> entriesOnlyOnLeft() {
       return ;
     }
 
     @Override
     public Map<K, V> entriesOnlyOnRight() {
       return ;
     }
 
     @Override
     public Map<K, V> entriesInCommon() {
       return ;
     }
 
     @Override
     public Map<K, ValueDifference<V>> entriesDiffering() {
       return ;
     }
 
     @Override public boolean equals(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 (!.isEmpty()) {
         result.append(": only on left=").append();
       }
       if (!.isEmpty()) {
         result.append(": only on right=").append();
       }
       if (!.isEmpty()) {
         result.append(": value differences=").append();
       }
       return result.toString();
     }
   }
 
   static class ValueDifferenceImpl<V>
       implements MapDifference.ValueDifference<V> {
     private final V left;
     private final V right;
 
     static <V> ValueDifference<V> create(@Nullable V left, @Nullable V right) {
       return new ValueDifferenceImpl<V>(leftright);
     }
 
     private ValueDifferenceImpl(@Nullable V left, @Nullable V right) {
       this. = left;
       this. = right;
     }
 
     @Override
     public V leftValue() {
       return ;
     }
 
     @Override
     public V rightValue() {
       return ;
     }
 
     @Override public boolean equals(@Nullable Object object) {
       if (object instanceof MapDifference.ValueDifference) {
         MapDifference.ValueDifference<?> that =
             (MapDifference.ValueDifference<?>) object;
         return Objects.equal(this.that.leftValue())
             && Objects.equal(this.that.rightValue());
       }
       return false;
     }
 
     @Override public int hashCode() {
       return Objects.hashCode();
     }
 
     @Override public String toString() {
       return "(" +  + ", " +  + ")";
     }
   }

  
Computes the difference between two sorted maps, using the comparator of the left map, or 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 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 left.equals(right) instead of this method.

Parameters:
left the map to treat as the "left" map for purposes of comparison
right the map to treat as the "right" map for purposes of comparison
Returns:
the difference between the two maps
Since:
11.0
 
   public static <K, V> SortedMapDifference<K, V> difference(
       SortedMap<K, ? extends V> leftMap<? extends K, ? extends V> right) {
     checkNotNull(left);
     checkNotNull(right);
     Comparator<? super K> comparator = orNaturalOrder(left.comparator());
     SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
     SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
     onlyOnRight.putAll(right); // will whittle it down
     SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
     SortedMap<K, MapDifference.ValueDifference<V>> differences =
         Maps.newTreeMap(comparator);
     doDifference(leftright, Equivalence.equals(), onlyOnLeftonlyOnRightonBothdifferences);
     return new SortedMapDifferenceImpl<K, V>(onlyOnLeftonlyOnRightonBothdifferences);
   }
 
   static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
       implements SortedMapDifference<K, V> {
     SortedMapDifferenceImpl(SortedMap<K, V> onlyOnLeft,
         SortedMap<K, V> onlyOnRightSortedMap<K, V> onBoth,
         SortedMap<K, ValueDifference<V>> differences) {
       super(onlyOnLeftonlyOnRightonBothdifferences);
     }
 
     @Override public SortedMap<K, ValueDifference<V>> entriesDiffering() {
       return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
     }
 
     @Override public SortedMap<K, V> entriesInCommon() {
       return (SortedMap<K, V>) super.entriesInCommon();
     }
 
     @Override public SortedMap<K, V> entriesOnlyOnLeft() {
       return (SortedMap<K, V>) super.entriesOnlyOnLeft();
     }
 
     @Override public SortedMap<K, V> entriesOnlyOnRight() {
       return (SortedMap<K, V>) super.entriesOnlyOnRight();
     }
   }

  
Returns the specified comparator if not null; otherwise returns 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 <E> Comparator<? super E> orNaturalOrder(
       @Nullable Comparator<? super E> comparator) {
     if (comparator != null) { // can't use ? : because of javac bug 5080917
       return comparator;
     }
     return (Comparator<E>) Ordering.natural();
   }

  
Returns a live Map view whose keys are the contents of set and whose values are computed on demand using function. To get an immutable copy instead, use toMap(Iterable, Function).

Specifically, for each k in the backing set, the returned map has an entry mapping k to function.apply(k). The keySet, values, and 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 null, caution is required to make sure the set does not contain null, because the view cannot stop null from being added to the set.

Warning: This method assumes that for any instance k of key type K, k.equals(k2) implies that k2 is also of type K. Using a key type for which this may not hold, such as ArrayList, may risk a ClassCastException when calling methods on the resulting map view.

Since:
14.0
 
   @Beta
   public static <K, V> Map<K, V> asMap(
       Set<K> setFunction<? super K, V> function) {
     if (set instanceof SortedSet) {
       return asMap((SortedSet<K>) setfunction);
     } else {
       return new AsMapView<K, V>(setfunction);
     }
   }

  
Returns a view of the sorted set as a map, mapping keys from the set according to the specified function.

Specifically, for each k in the backing set, the returned map has an entry mapping k to function.apply(k). The keySet, values, and 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 null, caution is required to make sure the set does not contain null, because the view cannot stop null from being added to the set.

Warning: This method assumes that for any instance k of key type K, k.equals(k2) implies that k2 is also of type K. Using a key type for which this may not hold, such as ArrayList, may risk a ClassCastException when calling methods on the resulting map view.

Since:
14.0
 
   @Beta
   public static <K, V> SortedMap<K, V> asMap(
       SortedSet<K> setFunction<? super K, V> function) {
     return Platform.mapsAsMapSortedSet(setfunction);
   }
 
   static <K, V> SortedMap<K, V> asMapSortedIgnoreNavigable(SortedSet<K> set,
       Function<? super K, V> function) {
     return new SortedAsMapView<K, V>(setfunction);
   }

  
Returns a view of the navigable set as a map, mapping keys from the set according to the specified function.

Specifically, for each k in the backing set, the returned map has an entry mapping k to function.apply(k). The keySet, values, and 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 null, caution is required to make sure the set does not contain null, because the view cannot stop null from being added to the set.

Warning: This method assumes that for any instance k of key type K, k.equals(k2) implies that k2 is also of type K. Using a key type for which this may not hold, such as ArrayList, may risk a ClassCastException when calling methods on the resulting map view.

Since:
14.0
 
   @Beta
   @GwtIncompatible("NavigableMap")
   public static <K, V> NavigableMap<K, V> asMap(
       NavigableSet<K> setFunction<? super K, V> function) {
     return new NavigableAsMapView<K, V>(setfunction);
   }
 
   private static class AsMapView<K, V> extends ImprovedAbstractMap<K, V> {
 
     private final Set<K> set;
     final Function<? super K, V> function;
 
     Set<K> backingSet() {
       return ;
     }
 
     AsMapView(Set<K> setFunction<? super K, V> function) {
       this. = checkNotNull(set);
       this. = checkNotNull(function);
     }
 
     @Override
     public Set<K> createKeySet() {
       return removeOnlySet(backingSet());
     }
 
     @Override
     Collection<V> createValues() {
       return Collections2.transform();
     }
 
     @Override
     public int size() {
       return backingSet().size();
     }
 
     @Override
     public boolean containsKey(@Nullable Object key) {
       return backingSet().contains(key);
     }
 
     @Override
     public V get(@Nullable Object key) {
       if (Collections2.safeContains(backingSet(), key)) {
         @SuppressWarnings("unchecked"// unsafe, but Javadoc warns about it
         K k = (K) key;
         return .apply(k);
       } else {
         return null;
       }
     }
 
     @Override
     public V remove(@Nullable Object key) {
       if (backingSet().remove(key)) {
         @SuppressWarnings("unchecked"// unsafe, but Javadoc warns about it
         K k = (K) key;
         return .apply(k);
       } else {
         return null;
       }
     }
 
     @Override
     public void clear() {
       backingSet().clear();
     }
 
     @Override
     protected Set<Entry<K, V>> createEntrySet() {
       return new EntrySet<K, V>() {
         @Override
         Map<K, V> map() {
           return AsMapView.this;
         }
 
         @Override
         public Iterator<Entry<K, V>> iterator() {
           return asMapEntryIterator(backingSet(), );
         }
       };
     }
   }
 
   static <K, V> Iterator<Entry<K, V>> asMapEntryIterator(
       Set<K> setfinal Function<? super K, V> function) {
     return new TransformedIterator<K, Entry<K,V>>(set.iterator()) {
       @Override
       Entry<K, V> transform(final K key) {
         return immutableEntry(keyfunction.apply(key));
       }
     };
   }
 
   private static class SortedAsMapView<K, V> extends AsMapView<K, V>
       implements SortedMap<K, V> {
 
     SortedAsMapView(SortedSet<K> setFunction<? super K, V> function) {
       super(setfunction);
     }
 
     @Override
     SortedSet<K> backingSet() {
       return (SortedSet<K>) super.backingSet();
     }
 
     @Override
     public Comparator<? super K> comparator() {
       return backingSet().comparator();
     }
 
     @Override
     public Set<K> keySet() {
       return removeOnlySortedSet(backingSet());
     }
 
     @Override
     public SortedMap<K, V> subMap(K fromKey, K toKey) {
       return asMap(backingSet().subSet(fromKeytoKey), );
     }
 
     @Override
     public SortedMap<K, V> headMap(K toKey) {
       return asMap(backingSet().headSet(toKey), );
     }
 
     @Override
     public SortedMap<K, V> tailMap(K fromKey) {
       return asMap(backingSet().tailSet(fromKey), );
     }
 
     @Override
     public K firstKey() {
       return backingSet().first();
     }
 
     @Override
     public K lastKey() {
       return backingSet().last();
     }
   }
 
   @GwtIncompatible("NavigableMap")
   private static final class NavigableAsMapView<K, V>
       extends AbstractNavigableMap<K, V> {
     /*
      * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
      * NavigableMap methods.
      */
 
     private final NavigableSet<K> set;
     private final Function<? super K, V> function;
 
     NavigableAsMapView(NavigableSet<K> ksFunction<? super K, V> vFunction) {
       this. = checkNotNull(ks);
       this. = checkNotNull(vFunction);
     }
 
     @Override
     public NavigableMap<K, V> subMap(
         K fromKeyboolean fromInclusive, K toKeyboolean toInclusive) {
       return asMap(.subSet(fromKeyfromInclusivetoKeytoInclusive), );
     }
 
     @Override
     public NavigableMap<K, V> headMap(K toKeyboolean inclusive) {
       return asMap(.headSet(toKeyinclusive), );
     }
 
     @Override
     public NavigableMap<K, V> tailMap(K fromKeyboolean inclusive) {
       return asMap(.tailSet(fromKeyinclusive), );
     }
 
     @Override
     public Comparator<? super K> comparator() {
       return .comparator();
     }
 
     @Override
     @Nullable
     public V get(@Nullable Object key) {
       if (Collections2.safeContains(key)) {
         @SuppressWarnings("unchecked"// unsafe, but Javadoc warns about it
         K k = (K) key;
         return .apply(k);
       } else {
         return null;
       }
     }
 
     @Override
     public void clear() {
       .clear();
     }
 
     @Override
     Iterator<Entry<K, V>> entryIterator() {
       return asMapEntryIterator();
     }
 
     @Override
     Iterator<Entry<K, V>> descendingEntryIterator() {
       return descendingMap().entrySet().iterator();
     }
 
     @Override
     public NavigableSet<K> navigableKeySet() {
       return removeOnlyNavigableSet();
     }
 
     @Override
     public int size() {
       return .size();
     }
 
     @Override
     public NavigableMap<K, V> descendingMap() {
       return asMap(.descendingSet(), );
     }
   }
 
   private static <E> Set<E> removeOnlySet(final Set<E> set) {
     return new ForwardingSet<E>() {
       @Override
       protected Set<E> delegate() {
         return set;
       }
 
       @Override
       public boolean add(E element) {
         throw new UnsupportedOperationException();
       }
 
       @Override
       public boolean addAll(Collection<? extends E> es) {
         throw new UnsupportedOperationException();
       }
     };
   }
 
   private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) {
     return new ForwardingSortedSet<E>() {
       @Override
       protected SortedSet<E> delegate() {
         return set;
       }
 
       @Override
       public boolean add(E element) {
         throw new UnsupportedOperationException();
       }
 
       @Override
       public boolean addAll(Collection<? extends E> es) {
        throw new UnsupportedOperationException();
      }
      @Override
      public SortedSet<E> headSet(E toElement) {
        return removeOnlySortedSet(super.headSet(toElement));
      }
      @Override
      public SortedSet<E> subSet(E fromElement, E toElement) {
        return removeOnlySortedSet(super.subSet(fromElementtoElement));
      }
      @Override
      public SortedSet<E> tailSet(E fromElement) {
        return removeOnlySortedSet(super.tailSet(fromElement));
      }
    };
  }
  @GwtIncompatible("NavigableSet")
  private static <E> NavigableSet<E> removeOnlyNavigableSet(final NavigableSet<E> set) {
    return new ForwardingNavigableSet<E>() {
      @Override
      protected NavigableSet<E> delegate() {
        return set;
      }
      @Override
      public boolean add(E element) {
        throw new UnsupportedOperationException();
      }
      @Override
      public boolean addAll(Collection<? extends E> es) {
        throw new UnsupportedOperationException();
      }
      @Override
      public SortedSet<E> headSet(E toElement) {
        return removeOnlySortedSet(super.headSet(toElement));
      }
      @Override
      public SortedSet<E> subSet(E fromElement, E toElement) {
        return removeOnlySortedSet(
            super.subSet(fromElementtoElement));
      }
      @Override
      public SortedSet<E> tailSet(E fromElement) {
        return removeOnlySortedSet(super.tailSet(fromElement));
      }
      @Override
      public NavigableSet<E> headSet(E toElementboolean inclusive) {
        return removeOnlyNavigableSet(super.headSet(toElementinclusive));
      }
      @Override
      public NavigableSet<E> tailSet(E fromElementboolean inclusive) {
        return removeOnlyNavigableSet(super.tailSet(fromElementinclusive));
      }
      @Override
      public NavigableSet<E> subSet(E fromElementboolean fromInclusive,
          E toElementboolean toInclusive) {
        return removeOnlyNavigableSet(super.subSet(
            fromElementfromInclusivetoElementtoInclusive));
      }
      @Override
      public NavigableSet<E> descendingSet() {
        return removeOnlyNavigableSet(super.descendingSet());
      }
    };
  }

  
Returns an immutable map whose keys are the distinct elements of keys and whose value for each key was computed by valueFunction. The map's iteration order is the order of the first appearance of each key in keys.

If keys is a Set, a live view can be obtained instead of a copy using Maps.asMap(Set, Function).

Throws:
NullPointerException if any element of keys is null, or if valueFunction produces null for any key
Since:
14.0
  public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys,
      Function<? super K, V> valueFunction) {
    return toMap(keys.iterator(), valueFunction);
  }

  
Returns an immutable map whose keys are the distinct elements of keys and whose value for each key was computed by valueFunction. The map's iteration order is the order of the first appearance of each key in keys.

Throws:
NullPointerException if any element of keys is null, or if valueFunction produces null for any key
Since:
14.0
  public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys,
      Function<? super K, V> valueFunction) {
    checkNotNull(valueFunction);
    // Using LHM instead of a builder so as not to fail on duplicate keys
    Map<K, V> builder = newLinkedHashMap();
    while (keys.hasNext()) {
      K key = keys.next();
      builder.put(keyvalueFunction.apply(key));
    }
    return ImmutableMap.copyOf(builder);
  }

  
Returns an immutable map for which the Map.values are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.

Parameters:
values the values to use when constructing the Map
keyFunction the function used to produce the key for each value
Returns:
a map mapping the result of evaluating the function keyFunction on each value in the input collection to that value
Throws:
IllegalArgumentException if keyFunction produces the same key for more than one value in the input collection
NullPointerException if any elements of values is null, or if keyFunction produces null for any value
  public static <K, V> ImmutableMap<K, V> uniqueIndex(
      Iterable<V> valuesFunction<? super V, K> keyFunction) {
    return uniqueIndex(values.iterator(), keyFunction);
  }

  
Returns an immutable map for which the Map.values are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.

Parameters:
values the values to use when constructing the Map
keyFunction the function used to produce the key for each value
Returns:
a map mapping the result of evaluating the function keyFunction on each value in the input collection to that value
Throws:
IllegalArgumentException if keyFunction produces the same key for more than one value in the input collection
NullPointerException if any elements of values is null, or if keyFunction produces null for any value
Since:
10.0
  public static <K, V> ImmutableMap<K, V> uniqueIndex(
      Iterator<V> valuesFunction<? super V, K> keyFunction) {
    checkNotNull(keyFunction);
    ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
    while (values.hasNext()) {
      V value = values.next();
      builder.put(keyFunction.apply(value), value);
    }
    return builder.build();
  }

  
Creates an ImmutableMap<String, String> from a Properties instance. Properties normally derive from Map<Object, Object>, but they typically contain strings, which is awkward. This method lets you get a plain-old-Map out of a Properties.

Parameters:
properties a Properties object to be converted
Returns:
an immutable map containing all the entries in properties
Throws:
ClassCastException if any key in Properties is not a String
NullPointerException if any key or value in Properties is null
  @GwtIncompatible("java.util.Properties")
  public static ImmutableMap<StringStringfromProperties(
      Properties properties) {
    ImmutableMap.Builder<StringStringbuilder = ImmutableMap.builder();
    for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
      String key = (Stringe.nextElement();
      builder.put(keyproperties.getProperty(key));
    }
    return builder.build();
  }

  
Returns an immutable map entry with the specified key and value. The Entry.setValue operation throws an UnsupportedOperationException.

The returned entry is serializable.

Parameters:
key the key to be associated with the returned entry
value the value to be associated with the returned entry
  @GwtCompatible(serializable = true)
  public static <K, V> Entry<K, V> immutableEntry(
      @Nullable K key, @Nullable V value) {
    return new ImmutableEntry<K, V>(keyvalue);
  }

  
Returns an unmodifiable view of the specified set of entries. The Entry.setValue operation throws an UnsupportedOperationException, as do any operations that would modify the returned set.

Parameters:
entrySet the entries for which to return an unmodifiable view
Returns:
an unmodifiable view of the entries
  static <K, V> Set<Entry<K, V>> unmodifiableEntrySet(
      Set<Entry<K, V>> entrySet) {
    return new UnmodifiableEntrySet<K, V>(
        Collections.unmodifiableSet(entrySet));
  }

  
Returns an unmodifiable view of the specified map entry. The Entry.setValue operation throws an UnsupportedOperationException. This also has the side-effect of redefining equals to comply with the Entry contract, to avoid a possible nefarious implementation of equals.

Parameters:
entry the entry for which to return an unmodifiable view
Returns:
an unmodifiable view of the entry
  static <K, V> Entry<K, V> unmodifiableEntry(final Entry<? extends K, ? extends V> entry) {
    checkNotNull(entry);
    return new AbstractMapEntry<K, V>() {
      @Override public K getKey() {
        return entry.getKey();
      }
      @Override public V getValue() {
        return entry.getValue();
      }
    };
  }

  

See also:
Multimaps.unmodifiableEntries
  static class UnmodifiableEntries<K, V>
      extends ForwardingCollection<Entry<K, V>> {
    private final Collection<Entry<K, V>> entries;
    UnmodifiableEntries(Collection<Entry<K, V>> entries) {
      this. = entries;
    }
    @Override protected Collection<Entry<K, V>> delegate() {
      return ;
    }
    @Override public Iterator<Entry<K, V>> iterator() {
      final Iterator<Entry<K, V>> delegate = super.iterator();
      return new UnmodifiableIterator<Entry<K, V>>() {
        @Override
        public boolean hasNext() {
          return delegate.hasNext();
        }
        @Override public Entry<K, V> next() {
          return unmodifiableEntry(delegate.next());
        }
      };
    }
    // See java.util.Collections.UnmodifiableEntrySet for details on attacks.
    @Override public Object[] toArray() {
      return standardToArray();
    }
    @Override public <T> T[] toArray(T[] array) {
      return standardToArray(array);
    }
  }

  

See also:
Maps.unmodifiableEntrySet(Set)
  static class UnmodifiableEntrySet<K, V>
      extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
    UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
      super(entries);
    }
    // See java.util.Collections.UnmodifiableEntrySet for details on attacks.
    @Override public boolean equals(@Nullable Object object) {
      return Sets.equalsImpl(thisobject);
    }
    @Override public int hashCode() {
      return Sets.hashCodeImpl(this);
    }
  }

  
Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee serial access, it is critical that all access to the backing bimap is accomplished through the returned bimap.

It is imperative that the user manually synchronize on the returned map when accessing any of its collection views:

   BiMap<Long, String> map = Maps.synchronizedBiMap(
       HashBiMap.<Long, String>create());
   ...
   Set<Long> set = map.keySet();  // Needn't be in synchronized block
   ...
   synchronized (map) {  // Synchronizing on map, not set!
     Iterator<Long> it = set.iterator(); // Must be in synchronized block
     while (it.hasNext()) {
       foo(it.next());
     
   }}

Failure to follow this advice may result in non-deterministic behavior.

The returned bimap will be serializable if the specified bimap is serializable.

Parameters:
bimap the bimap to be wrapped in a synchronized view
Returns:
a sychronized view of the specified bimap
  public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
    return Synchronized.biMap(bimapnull);
  }

  
Returns an unmodifiable view of the specified bimap. This method allows modules to provide users with "read-only" access to internal bimaps. Query operations on the returned bimap "read through" to the specified bimap, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

The returned bimap will be serializable if the specified bimap is serializable.

Parameters:
bimap the bimap for which an unmodifiable view is to be returned
Returns:
an unmodifiable view of the specified bimap
  public static <K, V> BiMap<K, V> unmodifiableBiMap(
      BiMap<? extends K, ? extends V> bimap) {
    return new UnmodifiableBiMap<K, V>(bimapnull);
  }

  

See also:
Maps.unmodifiableBiMap(BiMap)
  private static class UnmodifiableBiMap<K, V>
      extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
    final Map<K, V> unmodifiableMap;
    final BiMap<? extends K, ? extends V> delegate;
    BiMap<V, K> inverse;
    transient Set<V> values;
    UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate,
        @Nullable BiMap<V, K> inverse) {
       = Collections.unmodifiableMap(delegate);
      this. = delegate;
      this. = inverse;
    }
    @Override protected Map<K, V> delegate() {
      return ;
    }
    @Override
    public V forcePut(K key, V value) {
      throw new UnsupportedOperationException();
    }
    @Override
    public BiMap<V, K> inverse() {
      BiMap<V, K> result = ;
      return (result == null)
          ?  = new UnmodifiableBiMap<V, K>(.inverse(), this)
          : result;
    }
    @Override public Set<V> values() {
      Set<V> result = ;
      return (result == null)
          ?  = Collections.unmodifiableSet(.values())
          : result;
    }
    private static final long serialVersionUID = 0;
  }

  
Returns a view of a map where each value is transformed by a function. All other properties of the map, such as iteration order, are left intact. For example, the code:
   Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
   Function<Integer, Double> sqrt =
       new Function<Integer, Double>() {
         public Double apply(Integer in) {
           return Math.sqrt((int) in);
         
       };
   Map<String, Double> transformed = Maps.transformValues(map, sqrt);
   System.out.println(transformed);}
... prints {a=2.0, b=3.0}.

Changes in the underlying map are reflected in this view. Conversely, this view supports removal operations, and these are reflected in the underlying map.

It's acceptable for the underlying map to contain null keys, and even null values provided that the function is capable of accepting null input. The transformed map might contain null values, if the function sometimes gives a null result.

The returned map is not thread-safe or serializable, even if the underlying map is.

The function is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue and Map.toString(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

  public static <K, V1, V2> Map<K, V2> transformValues(
      Map<K, V1> fromMapFunction<? super V1, V2> function) {
    return transformEntries(fromMapasEntryTransformer(function));
  }

  
Returns a view of a sorted map where each value is transformed by a function. All other properties of the map, such as iteration order, are left intact. For example, the code:
   SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
   Function<Integer, Double> sqrt =
       new Function<Integer, Double>() {
         public Double apply(Integer in) {
           return Math.sqrt((int) in);
         
       };
   SortedMap<String, Double> transformed =
        Maps.transformValues(map, sqrt);
   System.out.println(transformed);}
... prints {a=2.0, b=3.0}.

Changes in the underlying map are reflected in this view. Conversely, this view supports removal operations, and these are reflected in the underlying map.

It's acceptable for the underlying map to contain null keys, and even null values provided that the function is capable of accepting null input. The transformed map might contain null values, if the function sometimes gives a null result.

The returned map is not thread-safe or serializable, even if the underlying map is.

The function is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue and Map.toString(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

Since:
11.0
  public static <K, V1, V2> SortedMap<K, V2> transformValues(
      SortedMap<K, V1> fromMapFunction<? super V1, V2> function) {
    return transformEntries(fromMapasEntryTransformer(function));
  }

  
Returns a view of a navigable map where each value is transformed by a function. All other properties of the map, such as iteration order, are left intact. For example, the code:
   NavigableMap<String, Integer> map = Maps.newTreeMap();
   map.put("a", 4);
   map.put("b", 9);
   Function<Integer, Double> sqrt =
       new Function<Integer, Double>() {
         public Double apply(Integer in) {
           return Math.sqrt((int) in);
         
       };
   NavigableMap<String, Double> transformed =
        Maps.transformNavigableValues(map, sqrt);
   System.out.println(transformed);}
... prints {a=2.0, b=3.0}. Changes in the underlying map are reflected in this view. Conversely, this view supports removal operations, and these are reflected in the underlying map.

It's acceptable for the underlying map to contain null keys, and even null values provided that the function is capable of accepting null input. The transformed map might contain null values, if the function sometimes gives a null result.

The returned map is not thread-safe or serializable, even if the underlying map is.

The function is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the function will be applied many times for bulk operations like Map.containsValue and Map.toString(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

Since:
13.0
  @GwtIncompatible("NavigableMap")
  public static <K, V1, V2> NavigableMap<K, V2> transformValues(
      NavigableMap<K, V1> fromMapFunction<? super V1, V2> function) {
    return transformEntries(fromMapasEntryTransformer(function));
  }

  
Returns a view of a map whose values are derived from the original map's entries. In contrast to transformValues, this method's entry-transformation logic may depend on the key as well as the value.

All other properties of the transformed map, such as iteration order, are left intact. For example, the code:

   Map<String, Boolean> options =
       ImmutableMap.of("verbose", true, "sort", false);
   EntryTransformer<String, Boolean, String> flagPrefixer =
       new EntryTransformer<String, Boolean, String>() {
         public String transformEntry(String key, Boolean value) {
           return value ? key : "no" + key;
         
       };
   Map<String, String> transformed =
       Maps.transformEntries(options, flagPrefixer);
   System.out.println(transformed);}
... prints {verbose=verbose, sort=nosort}.

Changes in the underlying map are reflected in this view. Conversely, this view supports removal operations, and these are reflected in the underlying map.

It's acceptable for the underlying map to contain null keys and null values provided that the transformer is capable of accepting null inputs. The transformed map might contain null values if the transformer sometimes gives a null result.

The returned map is not thread-safe or serializable, even if the underlying map is.

The transformer is applied lazily, invoked when needed. This is necessary for the returned map to be a view, but it means that the transformer will be applied many times for bulk operations like Map.containsValue and Object.toString. For this to perform well, transformer should be fast. To avoid lazy evaluation when the returned map doesn't need to be a view, copy the returned map into a new map of your choosing.

Warning: This method assumes that for any instance k of EntryTransformer key type K, k.equals(k2) implies that k2 is also of type K. Using an EntryTransformer key type for which this may not hold, such as ArrayList, may risk a ClassCastException when calling methods on the transformed map.

Since:
7.0
  public static <K, V1, V2> Map<K, V2> transformEntries(