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 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() {}

  
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();
     boolean eq = true;
 
     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 {
           eq = false;
           differences.put(
               leftKey, ValueDifferenceImpl.create(leftValuerightValue));
         }
       } else {
         eq = false;
         onlyOnLeft.put(leftKeyleftValue);
       }
     }
 
     boolean areEqual = eq && onlyOnRight.isEmpty();
     return mapDifference(
         areEqualonlyOnLeftonlyOnRightonBothdifferences);
   }
 
   private static <K, V> MapDifference<K, V> mapDifference(boolean areEqual,
       Map<K, V> onlyOnLeftMap<K, V> onlyOnRightMap<K, V> onBoth,
       Map<K, ValueDifference<V>> differences) {
     return new MapDifferenceImpl<K, V>(areEqual,
         Collections.unmodifiableMap(onlyOnLeft),
         Collections.unmodifiableMap(onlyOnRight),
         Collections.unmodifiableMap(onBoth),
         Collections.unmodifiableMap(differences));
   }
 
   static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
     final boolean areEqual;
     final Map<K, V> onlyOnLeft;
     final Map<K, V> onlyOnRight;
     final Map<K, V> onBoth;
     final Map<K, ValueDifference<V>> differences;
 
     MapDifferenceImpl(boolean areEqualMap<K, V> onlyOnLeft,
         Map<K, V> onlyOnRightMap<K, V> onBoth,
         Map<K, ValueDifference<V>> differences) {
       this. = areEqual;
       this. = onlyOnLeft;
       this. = onlyOnRight;
       this. = onBoth;
       this. = differences;
     }
 
     @Override
     public boolean areEqual() {
       return ;
     }
 
     @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 () {
         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);
     boolean eq = true;
 
     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 (Objects.equal(leftValuerightValue)) {
           onBoth.put(leftKeyleftValue);
         } else {
           eq = false;
           differences.put(
               leftKey, ValueDifferenceImpl.create(leftValuerightValue));
         }
       } else {
         eq = false;
         onlyOnLeft.put(leftKeyleftValue);
       }
     }
 
     boolean areEqual = eq && onlyOnRight.isEmpty();
     return sortedMapDifference(
         areEqualonlyOnLeftonlyOnRightonBothdifferences);
   }
 
   private static <K, V> SortedMapDifference<K, V> sortedMapDifference(
       boolean areEqualSortedMap<K, V> onlyOnLeftSortedMap<K, V> onlyOnRight,
       SortedMap<K, V> onBothSortedMap<K, ValueDifference<V>> differences) {
     return new SortedMapDifferenceImpl<K, V>(areEqual,
         Collections.unmodifiableSortedMap(onlyOnLeft),
         Collections.unmodifiableSortedMap(onlyOnRight),
         Collections.unmodifiableSortedMap(onBoth),
         Collections.unmodifiableSortedMap(differences));
   }
 
   static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V>
       implements SortedMapDifference<K, V> {
     SortedMapDifferenceImpl(boolean areEqualSortedMap<K, V> onlyOnLeft,
         SortedMap<K, V> onlyOnRightSortedMap<K, V> onBoth,
         SortedMap<K, ValueDifference<V>> differences) {
       super(areEqualonlyOnLeftonlyOnRightonBothdifferences);
     }
 
     @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 view of the 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.

 
   @Beta
   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.

 
   @Beta
   static <K, V> SortedMap<K, V> asMap(
       SortedSet<K> setFunction<? super K, V> function) {
     // TODO: NavigableSet overloads
     return new SortedAsMapView<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> keySet() {
       // probably not worth caching
       return new ForwardingSet<K>() {
         @Override
         protected Set<K> delegate() {
           return ;
         }
 
         @Override
         public boolean add(K element) {
           throw new UnsupportedOperationException();
         }
 
         @Override
         public boolean addAll(Collection<? extends K> collection) {
           throw new UnsupportedOperationException();
         }
       };
     }
 
     @Override
     public Collection<V> values() {
       // probably not worth caching
       return Collections2.transform();
     }
 
     @Override
     public int size() {
       return .size();
     }
 
     @Override
     public boolean containsKey(@Nullable Object key) {
       return .contains(key);
     }
 
     @Override
     public V get(@Nullable Object key) {
       if (.contains(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 (.remove(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
     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() {
           final Iterator<K> backingIterator = .iterator();
           return new Iterator<Entry<K, V>>() {
             @Override
             public boolean hasNext() {
               return backingIterator.hasNext();
             }
 
             @Override
             public Entry<K, V> next() {
               K k = backingIterator.next();
               return Maps.immutableEntry(k.apply(k));
             }
 
             @Override
             public void remove() {
               backingIterator.remove();
             }
           };
         }
       };
     }
   }
 
   private static final class SortedAsMapView<K, V> extends AsMapView<K, V>
       implements SortedMap<K, V> {
 
     SortedAsMapView(SortedSet<K> setFunction<? super K, V> function) {
       super(setfunction);
     }
 
     @Override
     public Comparator<? super K> comparator() {
       return backingSet().comparator();
     }
 
     @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();
     }
 
     @Override
     SortedSet<K> backingSet() {
       return (SortedSet<K>) super.backingSet();
     }
   }

  
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<K, 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 ForwardingIterator<Entry<K, V>>() {
         @Override public Entry<K, V> next() {
           return unmodifiableEntry(super.next());
         }
 
         @Override public void remove() {
           throw new UnsupportedOperationException();
         }
 
         @Override protected Iterator<Entry<K, V>> delegate() {
           return delegate;
         }
       };
     }
 
     // See java.util.Collections.UnmodifiableEntrySet for details on attacks.
 
     @Override public boolean add(Entry<K, V> element) {
       throw new UnsupportedOperationException();
     }
 
     @Override public boolean addAll(
         Collection<? extends Entry<K, V>> collection) {
       throw new UnsupportedOperationException();
     }
 
     @Override public void clear() {
       throw new UnsupportedOperationException();
     }
 
     @Override public boolean remove(Object object) {
       throw new UnsupportedOperationException();
     }
 
     @Override public boolean removeAll(Collection<?> collection) {
       throw new UnsupportedOperationException();
     }
 
     @Override public boolean retainAll(Collection<?> collection) {
       throw new UnsupportedOperationException();
     }
 
     @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.transformSortedValues(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));
  }
  private static <K, V1, V2> EntryTransformer<K, V1, V2>
      asEntryTransformer(final Function<? super V1, V2> function) {
    checkNotNull(function);
    return new EntryTransformer<K, V1, V2>() {
      @Override
      public V2 transformEntry(K key, V1 value) {
        return function.apply(value);
      }
    };
  }

  
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(
      Map<K, V1> fromMap,
      EntryTransformer<? super K, ? super V1, V2> transformer) {
    if (fromMap instanceof SortedMap) {
      return transformEntries((SortedMap<K, V1>) fromMaptransformer);
    }
    return new TransformedEntriesMap<K, V1, V2>(fromMaptransformer);
  }

  
Returns a view of a sorted map whose values are derived from the original sorted 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 =
       ImmutableSortedMap.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 : "yes" + key;
         
       };
   SortedMap<String, String> transformed =
       LabsMaps.transformSortedEntries(options, flagPrefixer);
   System.out.println(transformed);}
... prints {sort=yessort, verbose=verbose}.

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:
11.0
  public static <K, V1, V2> SortedMap<K, V2> transformEntries(
      SortedMap<K, V1> fromMap,
      EntryTransformer<? super K, ? super V1, V2> transformer) {
    return Platform.mapsTransformEntriesSortedMap(fromMaptransformer);
  }

  
Returns a view of a navigable map whose values are derived from the original navigable 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:

   NavigableMap<String, Boolean> options = Maps.newTreeMap();
   options.put("verbose", false);
   options.put("sort", true);
   EntryTransformer<String, Boolean, String> flagPrefixer =
       new EntryTransformer<String, Boolean, String>() {
         public String transformEntry(String key, Boolean value) {
           return value ? key : ("yes" + key);
         
       };
   NavigableMap<String, String> transformed =
       LabsMaps.transformNavigableEntries(options, flagPrefixer);
   System.out.println(transformed);}
... prints {sort=yessort, verbose=verbose}.

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:
13.0
  @GwtIncompatible("NavigableMap")
  public static <K, V1, V2> NavigableMap<K, V2> transformEntries(
      final NavigableMap<K, V1> fromMap,
      EntryTransformer<? super K, ? super V1, V2> transformer) {
    return new TransformedEntriesNavigableMap<K, V1, V2>(fromMaptransformer);
  }
  static <K, V1, V2> SortedMap<K, V2> transformEntriesIgnoreNavigable(
      SortedMap<K, V1> fromMap,
      EntryTransformer<? super K, ? super V1, V2> transformer) {
    return new TransformedEntriesSortedMap<K, V1, V2>(fromMaptransformer);
  }

  
A transformation of the value of a key-value pair, using both key and value as inputs. To apply the transformation to a map, use Maps.transformEntries(Map, EntryTransformer).

Parameters:
<K> the key type of the input and output entries
<V1> the value type of the input entry
<V2> the value type of the output entry
Since:
7.0
  public interface EntryTransformer<K, V1, V2> {
    
Determines an output value based on a key-value pair. This method is generally expected, but not absolutely required, to have the following properties:
  • Its execution does not cause any observable side effects.
  • The computation is consistent with equals; that is, Objects.equal(k1, k2) && Objects.equal(v1, v2) implies that Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2)).

Throws:
NullPointerException if the key or value is null and this transformer does not accept null arguments
    V2 transformEntry(@Nullable K key, @Nullable V1 value);
  }
  static class TransformedEntriesMap<K, V1, V2>
      extends AbstractMap<K, V2> {
    final Map<K, V1> fromMap;
    final EntryTransformer<? super K, ? super V1, V2> transformer;
        Map<K, V1> fromMap,
        EntryTransformer<? super K, ? super V1, V2> transformer) {
      this. = checkNotNull(fromMap);
      this. = checkNotNull(transformer);
    }
    @Override public int size() {
      return .size();
    }
    @Override public boolean containsKey(Object key) {
      return .containsKey(key);
    }
    // safe as long as the user followed the <b>Warning</b> in the javadoc
    @SuppressWarnings("unchecked")
    @Override public V2 get(Object key) {
      V1 value = .get(key);
      return (value != null || .containsKey(key))
          ? .transformEntry((K) keyvalue)
          : null;
    }
    // safe as long as the user followed the <b>Warning</b> in the javadoc
    @SuppressWarnings("unchecked")
    @Override public V2 remove(Object key) {
      return .containsKey(key)
          ? .transformEntry((K) key.remove(key))
          : null;
    }
    @Override public void clear() {
      .clear();
    }
    @Override public Set<K> keySet() {
      return .keySet();
    }
    Set<Entry<K, V2>> entrySet;
    @Override public Set<Entry<K, V2>> entrySet() {
      Set<Entry<K, V2>> result = ;
      if (result == null) {
         = result = new EntrySet<K, V2>() {
          @Override Map<K, V2> map() {
            return TransformedEntriesMap.this;
          }
          @Override public Iterator<Entry<K, V2>> iterator() {
            return new TransformedIterator<Entry<K, V1>, Entry<K, V2>>(
                .entrySet().iterator()) {
              @Override
              Entry<K, V2> transform(final Entry<K, V1> entry) {
                return new AbstractMapEntry<K, V2>() {
                  @Override
                  public K getKey() {
                    return entry.getKey();
                  }
                  @Override
                  public V2 getValue() {
                    return .transformEntry(entry.getKey(), entry.getValue());
                  }
                };
              }
            };
          }
        };
      }
      return result;
    }
    Collection<V2> values;
    @Override public Collection<V2> values() {
      Collection<V2> result = ;
      if (result == null) {
        return  = new Values<K, V2>() {
          @Override Map<K, V2> map() {
            return TransformedEntriesMap.this;
          }
        };
      }
      return result;
    }
  }
  static class TransformedEntriesSortedMap<K, V1, V2>
      extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
    protected SortedMap<K, V1> fromMap() {
      return (SortedMap<K, V1>) ;
    }
    TransformedEntriesSortedMap(SortedMap<K, V1> fromMap,
        EntryTransformer<? super K, ? super V1, V2> transformer) {
      super(fromMaptransformer);
    }
    @Override public Comparator<? super K> comparator() {
      return fromMap().comparator();
    }
    @Override public K firstKey() {
      return fromMap().firstKey();
    }
    @Override public SortedMap<K, V2> headMap(K toKey) {
      return transformEntries(fromMap().headMap(toKey), );
    }
    @Override public K lastKey() {
      return fromMap().lastKey();
    }
    @Override public SortedMap<K, V2> subMap(K fromKey, K toKey) {
      return transformEntries(
          fromMap().subMap(fromKeytoKey), );
    }
    @Override public SortedMap<K, V2> tailMap(K fromKey) {
      return transformEntries(fromMap().tailMap(fromKey), );
    }
  }
  @GwtIncompatible("NavigableMap")
  private static class TransformedEntriesNavigableMap<K, V1, V2>
      extends TransformedEntriesSortedMap<K, V1, V2>
      implements NavigableMap<K, V2> {
        EntryTransformer<? super K, ? super V1, V2> transformer) {
      super(fromMaptransformer);
    }
    @Override public Entry<K, V2> ceilingEntry(K key) {
      return transformEntry(fromMap().ceilingEntry(key));
    }
    @Override public K ceilingKey(K key) {
      return fromMap().ceilingKey(key);
    }
    @Override public NavigableSet<K> descendingKeySet() {
      return fromMap().descendingKeySet();
    }
    @Override public NavigableMap<K, V2> descendingMap() {
    }
    @Override public Entry<K, V2> firstEntry() {
      return transformEntry(fromMap().firstEntry());
    }
    @Override public Entry<K, V2> floorEntry(K key) {
      return transformEntry(fromMap().floorEntry(key));
    }
    @Override public K floorKey(K key) {
      return fromMap().floorKey(key);
    }
    @Override