Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 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.checkNotNull;
 
 
 import java.util.List;
 
 import  javax.annotation.Nullable;

An immutable hash-based multiset. Does not permit null elements.

Its iterator orders elements according to the first appearance of the element among the items passed to the factory method or builder. When the multiset contains multiple instances of an element, those instances are consecutive in the iteration order.

See the Guava User Guide article on immutable collections.

Author(s):
Jared Levy
Louis Wasserman
Since:
2.0 (imported from Google Collections Library)
 
 @GwtCompatible(serializable = true)
 @SuppressWarnings("serial"// we're overriding default serialization
 // TODO(user): write an efficient asList() implementation
 public abstract class ImmutableMultiset<E> extends ImmutableCollection<E>
     implements Multiset<E> {

  
Returns the empty immutable multiset.
 
   @SuppressWarnings("unchecked"// all supported methods are covariant
   public static <E> ImmutableMultiset<E> of() {
   }

  
Returns an immutable multiset containing a single element.

Throws:
NullPointerException if element is null
Since:
6.0 (source-compatible since 2.0)
 
   @SuppressWarnings("unchecked"// generic array created but never written
   public static <E> ImmutableMultiset<E> of(E element) {
     return copyOfInternal(element);
   }

  
Returns an immutable multiset containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
6.0 (source-compatible since 2.0)
 
   @SuppressWarnings("unchecked"//
   public static <E> ImmutableMultiset<E> of(E e1, E e2) {
     return copyOfInternal(e1e2);
   }

  
Returns an immutable multiset containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
6.0 (source-compatible since 2.0)
 
   @SuppressWarnings("unchecked"//
   public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
     return copyOfInternal(e1e2e3);
   }

  
Returns an immutable multiset containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
6.0 (source-compatible since 2.0)
  @SuppressWarnings("unchecked"//
  public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
    return copyOfInternal(e1e2e3e4);
  }

  
Returns an immutable multiset containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
6.0 (source-compatible since 2.0)
  @SuppressWarnings("unchecked"//
  public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
    return copyOfInternal(e1e2e3e4e5);
  }

  
Returns an immutable multiset containing the given elements, in order.

Throws:
NullPointerException if any element is null
Since:
6.0 (source-compatible since 2.0)
  @SuppressWarnings("unchecked"//
  public static <E> ImmutableMultiset<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
    int size = others.length + 6;
    List<E> all = new ArrayList<E>(size);
    Collections.addAll(alle1e2e3e4e5e6);
    Collections.addAll(allothers);
    return copyOf(all);
  }

  
Returns an immutable multiset containing the given elements.

The multiset is ordered by the first occurrence of each element. For example, ImmutableMultiset.copyOf([2, 3, 1, 3]) yields a multiset with elements in the order 2, 3, 3, 1.

Throws:
NullPointerException if any of elements is null
Since:
6.0
  public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
    return copyOf(Arrays.asList(elements));
  }

  
Returns an immutable multiset containing the given elements.

The multiset is ordered by the first occurrence of each element. For example, ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3)) yields a multiset with elements in the order 2, 3, 3, 1.

Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change.

Note: Despite what the method name suggests, if elements is an ImmutableMultiset, no copy will actually be performed, and the given multiset itself will be returned.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableMultiset<E> copyOf(
      Iterable<? extends E> elements) {
    if (elements instanceof ImmutableMultiset) {
      @SuppressWarnings("unchecked"// all supported methods are covariant
      ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
      if (!result.isPartialView()) {
        return result;
      }
    }
    Multiset<? extends E> multiset = (elements instanceof Multiset)
        ? Multisets.cast(elements)
        : LinkedHashMultiset.create(elements);
    return copyOfInternal(multiset);
  }
  private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
    return copyOf(Arrays.asList(elements));
  }
  private static <E> ImmutableMultiset<E> copyOfInternal(
      Multiset<? extends E> multiset) {
    return copyFromEntries(multiset.entrySet());
  }
      Collection<? extends Entry<? extends E>> entries) {
    long size = 0;
    ImmutableMap.Builder<E, Integerbuilder = ImmutableMap.builder();
    for (Entry<? extends E> entry : entries) {
      int count = entry.getCount();
      if (count > 0) {
        // Since ImmutableMap.Builder throws an NPE if an element is null, no
        // other null checks are needed.
        builder.put(entry.getElement(), count);
        size += count;
      }
    }
    if (size == 0) {
      return of();
    }
    return new RegularImmutableMultiset<E>(
        builder.build(), Ints.saturatedCast(size));
  }

  
Returns an immutable multiset containing the given elements.

The multiset is ordered by the first occurrence of each element. For example, ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator()) yields a multiset with elements in the order 2, 3, 3, 1.

Throws:
NullPointerException if any of elements is null
  public static <E> ImmutableMultiset<E> copyOf(
      Iterator<? extends E> elements) {
    Multiset<E> multiset = LinkedHashMultiset.create();
    Iterators.addAll(multisetelements);
    return copyOfInternal(multiset);
  }
    final Iterator<Entry<E>> entryIterator = entrySet().iterator();
    return new UnmodifiableIterator<E>() {
      int remaining;
      E element;
      @Override
      public boolean hasNext() {
        return ( > 0) || entryIterator.hasNext();
      }
      @Override
      public E next() {
        if ( <= 0) {
          Entry<E> entry = entryIterator.next();
           = entry.getElement();
           = entry.getCount();
        }
        --;
        return ;
      }
    };
  }
  public boolean contains(@Nullable Object object) {
    return count(object) > 0;
  }
  public boolean containsAll(Collection<?> targets) {
    return elementSet().containsAll(targets);
  }

  
Guaranteed to throw an exception and leave the collection unmodified.

Throws:
UnsupportedOperationException always
  public final int add(E elementint occurrences) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the collection unmodified.

Throws:
UnsupportedOperationException always
  public final int remove(Object elementint occurrences) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the collection unmodified.

Throws:
UnsupportedOperationException always
  public final int setCount(E elementint count) {
    throw new UnsupportedOperationException();
  }

  
Guaranteed to throw an exception and leave the collection unmodified.

Throws:
UnsupportedOperationException always
  public final boolean setCount(E elementint oldCountint newCount) {
    throw new UnsupportedOperationException();
  }
  @Override public boolean equals(@Nullable Object object) {
    if (object == this) {
      return true;
    }
    if (object instanceof Multiset) {
      Multiset<?> that = (Multiset<?>) object;
      if (this.size() != that.size()) {
        return false;
      }
      for (Entry<?> entry : that.entrySet()) {
        if (count(entry.getElement()) != entry.getCount()) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  @Override public int hashCode() {
    return Sets.hashCodeImpl(entrySet());
  }
  @Override public String toString() {
    return entrySet().toString();
  }
  private transient ImmutableSet<Entry<E>> entrySet;
  public ImmutableSet<Entry<E>> entrySet() {
    ImmutableSet<Entry<E>> es = ;
    return (es == null) ? ( = createEntrySet()) : es;
  }
  abstract ImmutableSet<Entry<E>> createEntrySet();
  abstract class EntrySet extends ImmutableSet<Entry<E>> {
    @Override
    boolean isPartialView() {
      return ImmutableMultiset.this.isPartialView();
    }
    @Override
    public boolean contains(Object o) {
      if (o instanceof Entry) {
        Entry<?> entry = (Entry<?>) o;
        if (entry.getCount() <= 0) {
          return false;
        }
        int count = count(entry.getElement());
        return count == entry.getCount();
      }
      return false;
    }
    /*
     * TODO(hhchan): Revert once we have a separate, manual emulation of this
     * class.
     */
    @Override
    public Object[] toArray() {
      Object[] newArray = new Object[size()];
      return toArray(newArray);
    }
    /*
     * TODO(hhchan): Revert once we have a separate, manual emulation of this
     * class.
     */
    @Override
    public <T> T[] toArray(T[] other) {
      int size = size();
      if (other.length < size) {
        other = ObjectArrays.newArray(othersize);
      } else if (other.length > size) {
        other[size] = null;
      }
      // Writes will produce ArrayStoreException when the toArray() doc requires
      Object[] otherAsObjectArray = other;
      int index = 0;
      for (Entry<?> element : this) {
        otherAsObjectArray[index++] = element;
      }
      return other;
    }
    @Override
    public int hashCode() {
      return ImmutableMultiset.this.hashCode();
    }
    // We can't label this with @Override, because it doesn't override anything
    // in the GWT emulated version.
    // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
    Object writeReplace() {
      return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
    }
    private static final long serialVersionUID = 0;
  }
  static class EntrySetSerializedForm<E> implements Serializable {
    final ImmutableMultiset<E> multiset;
      this. = multiset;
    }
    Object readResolve() {
      return .entrySet();
    }
  }
  private static class SerializedForm implements Serializable {
    final Object[] elements;
    final int[] counts;
    SerializedForm(Multiset<?> multiset) {
      int distinct = multiset.entrySet().size();
       = new Object[distinct];
       = new int[distinct];
      int i = 0;
      for (Entry<?> entry : multiset.entrySet()) {
        [i] = entry.getElement();
        [i] = entry.getCount();
        i++;
      }
    }
    Object readResolve() {
      LinkedHashMultiset<Objectmultiset =
          LinkedHashMultiset.create(.);
      for (int i = 0; i < .i++) {
        multiset.add([i], [i]);
      }
      return ImmutableMultiset.copyOf(multiset);
    }
    private static final long serialVersionUID = 0;
  }
  // We can't label this with @Override, because it doesn't override anything
  // in the GWT emulated version.
    return new SerializedForm(this);
  }

  
Returns a new builder. The generated builder is equivalent to the builder created by the Builder constructor.
  public static <E> Builder<E> builder() {
    return new Builder<E>();
  }

  
A builder for creating immutable multiset instances, especially public static final multisets ("constant multisets"). Example:
 public static final ImmutableMultiset<Bean> BEANS =
       new ImmutableMultiset.Builder<Bean>()
           .addCopies(Bean.COCOA, 4)
           .addCopies(Bean.GARDEN, 6)
           .addCopies(Bean.RED, 8)
           .addCopies(Bean.BLACK_EYED, 10)
           .build();
Builder instances can be reused; it is safe to call build multiple times to build multiple multisets in series.

Since:
2.0 (imported from Google Collections Library)
  public static class Builder<E> extends ImmutableCollection.Builder<E> {
    final Multiset<E> contents;

    
Creates a new builder. The returned builder is equivalent to the builder generated by ImmutableMultiset.builder.
    public Builder() {
      this(LinkedHashMultiset.<E>create());
    }
    Builder(Multiset<E> contents) {
      this. = contents;
    }

    
Adds element to the ImmutableMultiset.

Parameters:
element the element to add
Returns:
this Builder object
Throws:
NullPointerException if element is null
    @Override public Builder<E> add(E element) {
      .add(checkNotNull(element));
      return this;
    }

    
Adds a number of occurrences of an element to this ImmutableMultiset.

Parameters:
element the element to add
occurrences the number of occurrences of the element to add. May be zero, in which case no change will be made.
Returns:
this Builder object
Throws:
NullPointerException if element is null
IllegalArgumentException if occurrences is negative, or if this operation would result in more than Integer.MAX_VALUE occurrences of the element
    public Builder<E> addCopies(E elementint occurrences) {
      .add(checkNotNull(element), occurrences);
      return this;
    }

    
Adds or removes the necessary occurrences of an element such that the element attains the desired count.

Parameters:
element the element to add or remove occurrences of
count the desired count of the element in this multiset
Returns:
this Builder object
Throws:
NullPointerException if element is null
IllegalArgumentException if count is negative
    public Builder<E> setCount(E elementint count) {
      .setCount(checkNotNull(element), count);
      return this;
    }

    
Adds each element of elements to the ImmutableMultiset.

Parameters:
elements the elements to add
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> add(E... elements) {
      super.add(elements);
      return this;
    }

    
Adds each element of elements to the ImmutableMultiset.

Parameters:
elements the Iterable to add to the ImmutableMultiset
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterable<? extends E> elements) {
      if (elements instanceof Multiset) {
        Multiset<? extends E> multiset = Multisets.cast(elements);
        for (Entry<? extends E> entry : multiset.entrySet()) {
          addCopies(entry.getElement(), entry.getCount());
        }
      } else {
        super.addAll(elements);
      }
      return this;
    }

    
Adds each element of elements to the ImmutableMultiset.

Parameters:
elements the elements to add to the ImmutableMultiset
Returns:
this Builder object
Throws:
NullPointerException if elements is null or contains a null element
    @Override public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    
Returns a newly-created ImmutableMultiset based on the contents of the Builder.
    @Override public ImmutableMultiset<E> build() {
      return copyOf();
    }
  }
New to GrepCode? Check out our FAQ X