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.collect.CollectPreconditions.checkRemove;
 
 
 import java.util.Map;
 import java.util.Set;
 
 import  javax.annotation.Nullable;

Implementation of Multimap that does not allow duplicate key-value entries and that returns collections whose iterators follow the ordering in which the data was added to the multimap.

The collections returned by keySet, keys, and asMap iterate through the keys in the order they were first added to the multimap. Similarly, get, removeAll, and replaceValues return collections that iterate through the values in the order they were added. The collections generated by entries and values iterate across the key-value mappings in the order they were added to the multimap.

The iteration ordering of the collections generated by keySet, keys, and asMap has a few subtleties. As long as the set of keys remains unchanged, adding or removing mappings does not affect the key iteration order. However, if you remove all values associated with a key and then add the key back to the multimap, that key will come last in the key iteration order.

The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect.

Keys and values may be null. All optional multimap methods are supported, and all returned views are modifiable.

This class is not threadsafe when any concurrent operations update the multimap. Concurrent read operations will work correctly. To allow concurrent update operations, wrap your multimap with a call to Multimaps.synchronizedSetMultimap.

See the Guava User Guide article on Multimap.

Author(s):
Jared Levy
Louis Wasserman
Since:
2.0 (imported from Google Collections Library)
 
 @GwtCompatible(serializable = true, emulated = true)
 public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> {

  
Creates a new, empty LinkedHashMultimap with the default initial capacities.
 
   public static <K, V> LinkedHashMultimap<K, V> create() {
   }

  
Constructs an empty LinkedHashMultimap with enough capacity to hold the specified numbers of keys and values without rehashing.

Parameters:
expectedKeys the expected number of distinct keys
expectedValuesPerKey the expected average number of values per key
Throws:
IllegalArgumentException if expectedKeys or expectedValuesPerKey is negative
  public static <K, V> LinkedHashMultimap<K, V> create(
      int expectedKeysint expectedValuesPerKey) {
    return new LinkedHashMultimap<K, V>(
        Maps.capacity(expectedKeys),
        Maps.capacity(expectedValuesPerKey));
  }

  
Constructs a LinkedHashMultimap with the same mappings as the specified multimap. If a key-value mapping appears multiple times in the input multimap, it only appears once in the constructed multimap. The new multimap has the same Multimap.entries() iteration order as the input multimap, except for excluding duplicate mappings.

Parameters:
multimap the multimap whose contents are copied to this multimap
  public static <K, V> LinkedHashMultimap<K, V> create(
      Multimap<? extends K, ? extends V> multimap) {
    LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), );
    result.putAll(multimap);
    return result;
  }
  private interface ValueSetLink<K, V> {
    void setPredecessorInValueSet(ValueSetLink<K, V> entry);
    void setSuccessorInValueSet(ValueSetLink<K, V> entry);
  }
  private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> predValueSetLink<K, V> succ) {
    pred.setSuccessorInValueSet(succ);
    succ.setPredecessorInValueSet(pred);
  }
  private static <K, V> void succeedsInMultimap(
      ValueEntry<K, V> predValueEntry<K, V> succ) {
    pred.setSuccessorInMultimap(succ);
    succ.setPredecessorInMultimap(pred);
  }
  private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) {
  }
  private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) {
  }

  
LinkedHashMultimap entries are in no less than three coexisting linked lists: a bucket in the hash table for a Set<V> associated with a key, the linked list of insertion-ordered entries in that Set<V>, and the linked list of entries in the LinkedHashMultimap as a whole.
  static final class ValueEntry<K, V> extends ImmutableEntry<K, V>
      implements ValueSetLink<K, V> {
    final int smearedValueHash;
    @Nullable ValueEntry<K, V> nextInValueBucket;
    ValueEntry(@Nullable K key, @Nullable V valueint smearedValueHash,
        @Nullable ValueEntry<K, V> nextInValueBucket) {
      super(keyvalue);
      this. = smearedValueHash;
      this. = nextInValueBucket;
    }
    
    boolean matchesValue(@Nullable Object vint smearedVHash) {
      return  == smearedVHash && Objects.equal(getValue(), v);
    }
    @Override
    public ValueSetLink<K, V> getPredecessorInValueSet() {
      return ;
    }
    @Override
    public ValueSetLink<K, V> getSuccessorInValueSet() {
      return ;
    }
    @Override
    public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
       = entry;
    }
    @Override
    public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
       = entry;
    }
    public ValueEntry<K, V> getPredecessorInMultimap() {
      return ;
    }
    public ValueEntry<K, V> getSuccessorInMultimap() {
      return ;
    }
    public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) {
      this. = multimapSuccessor;
    }
    public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) {
      this. = multimapPredecessor;
    }
  }
  private static final int DEFAULT_KEY_CAPACITY = 16;
  private static final int DEFAULT_VALUE_SET_CAPACITY = 2;
  @VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0;
  private transient ValueEntry<K, V> multimapHeaderEntry;
  private LinkedHashMultimap(int keyCapacityint valueSetCapacity) {
    super(new LinkedHashMap<K, Collection<V>>(keyCapacity));
    checkArgument(valueSetCapacity >= 0,
        "expectedValuesPerKey must be >= 0 but was %s"valueSetCapacity);
    this. = valueSetCapacity;
    this. = new ValueEntry<K, V>(nullnull, 0, null);
  }

  

Creates an empty LinkedHashSet for a collection of values for one key.

Returns:
a new LinkedHashSet containing a collection of values for one key
    return new LinkedHashSet<V>();
  }

  

Creates a decorated insertion-ordered set that also keeps track of the order in which key-value pairs are added to the multimap.

Parameters:
key key to associate with values in the collection
Returns:
a new decorated set containing a collection of values for one key
  Collection<V> createCollection(K key) {
    return new ValueSet(key);
  }

  

If values is not empty and the multimap already contains a mapping for key, the keySet() ordering is unchanged. However, the provided values always come last in the entries() and values() iteration orderings.

  public Set<V> replaceValues(@Nullable K keyIterable<? extends V> values) {
    return super.replaceValues(keyvalues);
  }

  
Returns a set of all key-value pairs. Changes to the returned set will update the underlying multimap, and vice versa. The entries set does not support the add or addAll operations.

The iterator generated by the returned set traverses the entries in the order they were added to the multimap.

Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the time the entry is returned by a method call to the collection or its iterator.

  @Override public Set<Map.Entry<K, V>> entries() {
    return super.entries();
  }

  
Returns a collection of all values in the multimap. Changes to the returned collection will update the underlying multimap, and vice versa.

The iterator generated by the returned collection traverses the values in the order they were added to the multimap.

  @Override public Collection<V> values() {
    return super.values();
  }
  final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> {
    /*
     * We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory
     * consumption.
     */
    private final K key;
    @VisibleForTesting ValueEntry<K, V>[] hashTable;
    private int size = 0;
    private int modCount = 0;
    // We use the set object itself as the end of the linked list, avoiding an unnecessary
    // entry object per key.
    private ValueSetLink<K, V> firstEntry;
    private ValueSetLink<K, V> lastEntry;
    ValueSet(K keyint expectedValues) {
      this. = key;
      this. = this;
      this. = this;
      // Round expected values up to a power of 2 to get the table size.
      int tableSize = Hashing.closedTableSize(expectedValues);
      
      @SuppressWarnings("unchecked")
      ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize];
      this. = hashTable;
    }
    
    private int mask() {
      return . - 1;
    }
    @Override
    public ValueSetLink<K, V> getPredecessorInValueSet() {
      return ;
    }
    @Override
    public ValueSetLink<K, V> getSuccessorInValueSet() {
      return ;
    }
    @Override
    public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
       = entry;
    }
    @Override
    public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
       = entry;
    }
    @Override
    public Iterator<V> iterator() {
      return new Iterator<V>() {
        ValueSetLink<K, V> nextEntry = ;
        ValueEntry<K, V> toRemove;
        int expectedModCount = ;
        private void checkForComodification() {
          if ( != ) {
            throw new ConcurrentModificationException();
          }
        }
        @Override
        public boolean hasNext() {
          checkForComodification();
          return  != ValueSet.this;
        }
        @Override
        public V next() {
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
          ValueEntry<K, V> entry = (ValueEntry<K, V>) ;
          V result = entry.getValue();
           = entry;
           = entry.getSuccessorInValueSet();
          return result;
        }
        @Override
        public void remove() {
          checkForComodification();
          checkRemove( != null);
          ValueSet.this.remove(.getValue());
           = ;
           = null;
        }
      };
    }
    @Override
    public int size() {
      return ;
    }
    @Override
    public boolean contains(@Nullable Object o) {
      int smearedHash = Hashing.smearedHash(o);
      for (ValueEntry<K, V> entry = [smearedHash & mask()]; entry != null;
          entry = entry.nextInValueBucket) {
        if (entry.matchesValue(osmearedHash)) {
          return true;
        }
      }
      return false;
    }
    @Override
    public boolean add(@Nullable V value) {
      int smearedHash = Hashing.smearedHash(value);
      int bucket = smearedHash & mask();
      ValueEntry<K, V> rowHead = [bucket];
      for (ValueEntry<K, V> entry = rowHeadentry != null;
          entry = entry.nextInValueBucket) {
        if (entry.matchesValue(valuesmearedHash)) {
          return false;
        }
      }
      ValueEntry<K, V> newEntry = new ValueEntry<K, V>(valuesmearedHashrowHead);
      succeedsInValueSet(newEntry);
      succeedsInValueSet(newEntrythis);
      [bucket] = newEntry;
      ++;
      ++;
      rehashIfNecessary();
      return true;
    }
    private void rehashIfNecessary() {
      if (Hashing.needsResizing(.)) {
        @SuppressWarnings("unchecked")
        ValueEntry<K, V>[] hashTable = new ValueEntry[this..length * 2];
        this. = hashTable;
        int mask = hashTable.length - 1;
        for (ValueSetLink<K, V> entry = ;
            entry != thisentry = entry.getSuccessorInValueSet()) {
          ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
          int bucket = valueEntry.smearedValueHash & mask;
          valueEntry.nextInValueBucket = hashTable[bucket];
          hashTable[bucket] = valueEntry;
        }
      }
    }
    @Override
    public boolean remove(@Nullable Object o) {
      int smearedHash = Hashing.smearedHash(o);
      int bucket = smearedHash & mask();
      ValueEntry<K, V> prev = null;
      for (ValueEntry<K, V> entry = [bucket]; entry != null;
           prev = entryentry = entry.nextInValueBucket) {
        if (entry.matchesValue(osmearedHash)) {
          if (prev == null) {
            // first entry in the bucket
            [bucket] = entry.nextInValueBucket;
          } else {
            prev.nextInValueBucket = entry.nextInValueBucket;
          }
          deleteFromValueSet(entry);
          deleteFromMultimap(entry);
          --;
          ++;
          return true;
        }
      }
      return false;
    }
    @Override
    public void clear() {
      Arrays.fill(null);
       = 0;
      for (ValueSetLink<K, V> entry = ;
           entry != thisentry = entry.getSuccessorInValueSet()) {
        ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
        deleteFromMultimap(valueEntry);
      }
      succeedsInValueSet(thisthis);
      ++;
    }
  }
    return new Iterator<Map.Entry<K, V>>() {
      ValueEntry<K, V> toRemove;
      @Override
      public boolean hasNext() {
        return  != ;
      }
      @Override
      public Map.Entry<K, V> next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        ValueEntry<K, V> result = ;
         = result;
        return result;
      }
      @Override
      public void remove() {
        checkRemove( != null);
         = null;
      }
    };
  }
  
    return Maps.valueIterator(entryIterator());
  }
  public void clear() {
    super.clear();
  }

  

SerialData:
the expected values per key, the number of distinct keys, the number of entries, and the entries in order
  @GwtIncompatible("java.io.ObjectOutputStream")
  private void writeObject(ObjectOutputStream streamthrows IOException {
    stream.defaultWriteObject();
    stream.writeInt();
    stream.writeInt(keySet().size());
    for (K key : keySet()) {
      stream.writeObject(key);
    }
    stream.writeInt(size());
    for (Map.Entry<K, V> entry : entries()) {
      stream.writeObject(entry.getKey());
      stream.writeObject(entry.getValue());
    }
  }
  @GwtIncompatible("java.io.ObjectInputStream")
  private void readObject(ObjectInputStream stream)
      throws IOExceptionClassNotFoundException {
    stream.defaultReadObject();
     = new ValueEntry<K, V>(nullnull, 0, null);
     = stream.readInt();
    int distinctKeys = stream.readInt();
    Map<K, Collection<V>> map =
        new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys));
    for (int i = 0; i < distinctKeysi++) {
      @SuppressWarnings("unchecked")
      K key = (K) stream.readObject();
      map.put(keycreateCollection(key));
    }
    int entries = stream.readInt();
    for (int i = 0; i < entriesi++) {
      @SuppressWarnings("unchecked")
      K key = (K) stream.readObject();
      @SuppressWarnings("unchecked")
      V value = (V) stream.readObject();
      map.get(key).add(value);
    }
    setMap(map);
  }
  @GwtIncompatible("java serialization not supported")
  private static final long serialVersionUID = 1;
New to GrepCode? Check out our FAQ X