org.testifyproject.guava.common.collect.ImmutableMultiset Maven / Gradle / Ivy
/*
* 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 org.testifyproject.guava.common.collect;
import static org.testifyproject.guava.common.base.Preconditions.checkNotNull;
import org.testifyproject.guava.common.annotations.Beta;
import org.testifyproject.guava.common.annotations.GwtCompatible;
import org.testifyproject.guava.common.annotations.GwtIncompatible;
import org.testifyproject.guava.errorprone.annotations.CanIgnoreReturnValue;
import org.testifyproject.guava.errorprone.annotations.concurrent.LazyInit;
import org.testifyproject.guava.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.stream.Collector;
import javax.annotation.Nullable;
/**
* A {@link Multiset} whose contents will never change, with many other important properties
* detailed at {@link ImmutableCollection}.
*
* Grouped iteration. In all current implementations, duplicate elements always appear
* consecutively when iterating. Elements iterate in order by the first appearance of
* that element when the multiset was created.
*
*
See the Guava User Guide article on
* immutable collections.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableMultiset extends ImmutableMultisetGwtSerializationDependencies
implements Multiset {
/**
* Returns a {@code Collector} that accumulates the input elements into a new
* {@code ImmutableMultiset}. Elements iterate in order by the first appearance of that
* element in encounter order.
*
* @since 21.0
*/
@Beta
public static Collector> toImmutableMultiset() {
return toImmutableMultiset(Function.identity(), e -> 1);
}
/**
* Returns a {@code Collector} that accumulates elements into an {@code ImmutableMultiset} whose
* elements are the result of applying {@code elementFunction} to the inputs, with counts equal to
* the result of applying {@code countFunction} to the inputs.
*
* If the mapped elements contain duplicates (according to {@link Object#equals}), the first
* occurrence in encounter order appears in the resulting multiset, with count equal to the sum of
* the outputs of {@code countFunction.applyAsInt(t)} for each {@code t} mapped to that element.
*
* @since 22.0
*/
public static Collector> toImmutableMultiset(
Function super T, ? extends E> elementFunction, ToIntFunction super T> countFunction) {
checkNotNull(elementFunction);
checkNotNull(countFunction);
return Collector.of(
LinkedHashMultiset::create,
(multiset, t) ->
multiset.add(checkNotNull(elementFunction.apply(t)), countFunction.applyAsInt(t)),
(multiset1, multiset2) -> {
multiset1.addAll(multiset2);
return multiset1;
},
(Multiset multiset) -> copyFromEntries(multiset.entrySet()));
}
/**
* Returns the empty immutable multiset.
*/
@SuppressWarnings("unchecked") // all supported methods are covariant
public static ImmutableMultiset of() {
return (ImmutableMultiset) RegularImmutableMultiset.EMPTY;
}
/**
* Returns an immutable multiset containing a single element.
*
* @throws NullPointerException if {@code element} is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") // generic array created but never written
public static ImmutableMultiset of(E element) {
return copyFromElements(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 ImmutableMultiset of(E e1, E e2) {
return copyFromElements(e1, e2);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3) {
return copyFromElements(e1, e2, e3);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3, E e4) {
return copyFromElements(e1, e2, e3, e4);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3, E e4, E e5) {
return copyFromElements(e1, e2, e3, e4, e5);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any element is null
* @since 6.0 (source-compatible since 2.0)
*/
@SuppressWarnings("unchecked") //
public static ImmutableMultiset of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
return new Builder().add(e1).add(e2).add(e3).add(e4).add(e5).add(e6).add(others).build();
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
* @since 6.0
*/
public static ImmutableMultiset copyOf(E[] elements) {
return copyFromElements(elements);
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static ImmutableMultiset copyOf(Iterable extends E> elements) {
if (elements instanceof ImmutableMultiset) {
@SuppressWarnings("unchecked") // all supported methods are covariant
ImmutableMultiset result = (ImmutableMultiset) elements;
if (!result.isPartialView()) {
return result;
}
}
Multiset extends E> multiset =
(elements instanceof Multiset)
? Multisets.cast(elements)
: LinkedHashMultiset.create(elements);
return copyFromEntries(multiset.entrySet());
}
private static ImmutableMultiset copyFromElements(E... elements) {
Multiset multiset = LinkedHashMultiset.create();
Collections.addAll(multiset, elements);
return copyFromEntries(multiset.entrySet());
}
static ImmutableMultiset copyFromEntries(
Collection extends Entry extends E>> entries) {
if (entries.isEmpty()) {
return of();
} else {
return new RegularImmutableMultiset(entries);
}
}
/**
* Returns an immutable multiset containing the given elements, in the "grouped iteration order"
* described in the class documentation.
*
* @throws NullPointerException if any of {@code elements} is null
*/
public static ImmutableMultiset copyOf(Iterator extends E> elements) {
Multiset multiset = LinkedHashMultiset.create();
Iterators.addAll(multiset, elements);
return copyFromEntries(multiset.entrySet());
}
ImmutableMultiset() {}
@Override
public UnmodifiableIterator iterator() {
final Iterator> entryIterator = entrySet().iterator();
return new UnmodifiableIterator() {
int remaining;
E element;
@Override
public boolean hasNext() {
return (remaining > 0) || entryIterator.hasNext();
}
@Override
public E next() {
if (remaining <= 0) {
Entry entry = entryIterator.next();
element = entry.getElement();
remaining = entry.getCount();
}
remaining--;
return element;
}
};
}
@LazyInit
private transient ImmutableList asList;
@Override
public ImmutableList asList() {
ImmutableList result = asList;
return (result == null) ? asList = super.asList() : result;
}
@Override
public boolean contains(@Nullable Object object) {
return count(object) > 0;
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final int add(E element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final int remove(Object element, int occurrences) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final int setCount(E element, int count) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the collection unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@CanIgnoreReturnValue
@Deprecated
@Override
public final boolean setCount(E element, int oldCount, int newCount) {
throw new UnsupportedOperationException();
}
@GwtIncompatible // not present in emulated superclass
@Override
int copyIntoArray(Object[] dst, int offset) {
for (Multiset.Entry entry : entrySet()) {
Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
offset += entry.getCount();
}
return offset;
}
@Override
public boolean equals(@Nullable Object object) {
return Multisets.equalsImpl(this, object);
}
@Override
public int hashCode() {
return Sets.hashCodeImpl(entrySet());
}
@Override
public String toString() {
return entrySet().toString();
}
/** @since 21.0 (present with return type {@code Set} since 2.0) */
@Override
public abstract ImmutableSet elementSet();
@LazyInit
private transient ImmutableSet> entrySet;
@Override
public ImmutableSet> entrySet() {
ImmutableSet> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
private final ImmutableSet> createEntrySet() {
return isEmpty() ? ImmutableSet.>of() : new EntrySet();
}
abstract Entry getEntry(int index);
@WeakOuter
private final class EntrySet extends ImmutableSet.Indexed> {
@Override
boolean isPartialView() {
return ImmutableMultiset.this.isPartialView();
}
@Override
Entry get(int index) {
return getEntry(index);
}
@Override
public int size() {
return elementSet().size();
}
@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;
}
@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(ImmutableMultiset.this);
}
private static final long serialVersionUID = 0;
}
static class EntrySetSerializedForm implements Serializable {
final ImmutableMultiset multiset;
EntrySetSerializedForm(ImmutableMultiset multiset) {
this.multiset = multiset;
}
Object readResolve() {
return multiset.entrySet();
}
}
private static class SerializedForm implements Serializable {
final Object[] elements;
final int[] counts;
SerializedForm(Multiset> multiset) {
int distinct = multiset.entrySet().size();
elements = new Object[distinct];
counts = new int[distinct];
int i = 0;
for (Entry> entry : multiset.entrySet()) {
elements[i] = entry.getElement();
counts[i] = entry.getCount();
i++;
}
}
Object readResolve() {
LinkedHashMultiset