code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2011 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 static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.primitives.Ints; import javax.annotation.Nullable; /** * An immutable sorted multiset with one or more distinct elements. * * @author Louis Wasserman */ @SuppressWarnings("serial") // uses writeReplace, not default serialization final class RegularImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> { private final transient RegularImmutableSortedSet<E> elementSet; private final transient int[] counts; private final transient long[] cumulativeCounts; private final transient int offset; private final transient int length; RegularImmutableSortedMultiset( RegularImmutableSortedSet<E> elementSet, int[] counts, long[] cumulativeCounts, int offset, int length) { this.elementSet = elementSet; this.counts = counts; this.cumulativeCounts = cumulativeCounts; this.offset = offset; this.length = length; } @Override Entry<E> getEntry(int index) { return Multisets.immutableEntry( elementSet.asList().get(index), counts[offset + index]); } @Override public Entry<E> firstEntry() { return getEntry(0); } @Override public Entry<E> lastEntry() { return getEntry(length - 1); } @Override public int count(@Nullable Object element) { int index = elementSet.indexOf(element); return (index == -1) ? 0 : counts[index + offset]; } @Override public int size() { long size = cumulativeCounts[offset + length] - cumulativeCounts[offset]; return Ints.saturatedCast(size); } @Override public ImmutableSortedSet<E> elementSet() { return elementSet; } @Override public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return getSubMultiset(0, elementSet.headIndex(upperBound, checkNotNull(boundType) == CLOSED)); } @Override public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return getSubMultiset(elementSet.tailIndex(lowerBound, checkNotNull(boundType) == CLOSED), length); } ImmutableSortedMultiset<E> getSubMultiset(int from, int to) { checkPositionIndexes(from, to, length); if (from == to) { return emptyMultiset(comparator()); } else if (from == 0 && to == length) { return this; } else { RegularImmutableSortedSet<E> subElementSet = (RegularImmutableSortedSet<E>) elementSet.getSubSet(from, to); return new RegularImmutableSortedMultiset<E>( subElementSet, counts, cumulativeCounts, offset + from, to - from); } } @Override boolean isPartialView() { return offset > 0 || length < counts.length; } }
Java
/* * 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 com.google.common.annotations.Beta; /** * Provides equivalent behavior to {@link String#intern} for other immutable * types. * * @author Kevin Bourrillion * @since 3.0 */ @Beta public interface Interner<E> { /** * Chooses and returns the representative instance for any of a collection of * instances that are equal to each other. If two {@linkplain Object#equals * equal} inputs are given to this method, both calls will return the same * instance. That is, {@code intern(a).equals(a)} always holds, and {@code * intern(a) == intern(b)} if and only if {@code a.equals(b)}. Note that * {@code intern(a)} is permitted to return one instance now and a different * instance later if the original interned instance was garbage-collected. * * <p><b>Warning:</b> do not use with mutable objects. * * @throws NullPointerException if {@code sample} is null */ E intern(E sample); }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting * all optional operations. * * <p>Like all {@code RangeMap} implementations, this supports neither null * keys nor null values. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtIncompatible("NavigableMap") public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> { private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound; public static <K extends Comparable, V> TreeRangeMap<K, V> create() { return new TreeRangeMap<K, V>(); } private TreeRangeMap() { this.entriesByLowerBound = Maps.newTreeMap(); } private static final class RangeMapEntry<K extends Comparable, V> extends AbstractMapEntry<Range<K>, V> { private final Range<K> range; private final V value; RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) { this(Range.create(lowerBound, upperBound), value); } RangeMapEntry(Range<K> range, V value) { this.range = range; this.value = value; } @Override public Range<K> getKey() { return range; } @Override public V getValue() { return value; } public boolean contains(K value) { return range.contains(value); } Cut<K> getLowerBound() { return range.lowerBound; } Cut<K> getUpperBound() { return range.upperBound; } } @Override @Nullable public V get(K key) { Entry<Range<K>, V> entry = getEntry(key); return (entry == null) ? null : entry.getValue(); } @Override @Nullable public Entry<Range<K>, V> getEntry(K key) { Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry = entriesByLowerBound.floorEntry(Cut.belowValue(key)); if (mapEntry != null && mapEntry.getValue().contains(key)) { return mapEntry.getValue(); } else { return null; } } @Override public void put(Range<K> range, V value) { if (!range.isEmpty()) { checkNotNull(value); remove(range); entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value)); } } @Override public void putAll(RangeMap<K, V> rangeMap) { for (Map.Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { entriesByLowerBound.clear(); } @Override public Range<K> span() { Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry(); Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry(); if (firstEntry == null) { throw new NoSuchElementException(); } return Range.create( firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound); } private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) { entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value)); } @Override public void remove(Range<K> rangeToRemove) { if (rangeToRemove.isEmpty()) { return; } /* * The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to * indicate the bounds of ranges in the range map. */ Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate = entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound); if (mapEntryBelowToTruncate != null) { // we know ( [ RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue(); if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) { // we know ( [ ) if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) { // we know ( [ ] ), so insert the range ] ) back into the map -- // it's being split apart putRangeMapEntry(rangeToRemove.upperBound, rangeMapEntry.getUpperBound(), mapEntryBelowToTruncate.getValue().getValue()); } // overwrite mapEntryToTruncateBelow with a truncated range putRangeMapEntry(rangeMapEntry.getLowerBound(), rangeToRemove.lowerBound, mapEntryBelowToTruncate.getValue().getValue()); } } Map.Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate = entriesByLowerBound.lowerEntry(rangeToRemove.upperBound); if (mapEntryAboveToTruncate != null) { // we know ( ] RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue(); if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) { // we know ( ] ), and since we dealt with truncating below already, // we know [ ( ] ) putRangeMapEntry(rangeToRemove.upperBound, rangeMapEntry.getUpperBound(), mapEntryAboveToTruncate.getValue().getValue()); entriesByLowerBound.remove(rangeToRemove.lowerBound); } } entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); } @Override public Map<Range<K>, V> asMapOfRanges() { return new AsMapOfRanges(); } private final class AsMapOfRanges extends AbstractMap<Range<K>, V> { @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public V get(@Nullable Object key) { if (key instanceof Range) { Range<?> range = (Range<?>) key; RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound); if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) { return rangeMapEntry.getValue(); } } return null; } @Override public Set<Entry<Range<K>, V>> entrySet() { return new AbstractSet<Entry<Range<K>, V>>() { @SuppressWarnings("unchecked") // it's safe to upcast iterators @Override public Iterator<Entry<Range<K>, V>> iterator() { return (Iterator) entriesByLowerBound.values().iterator(); } @Override public int size() { return entriesByLowerBound.size(); } }; } } @Override public RangeMap<K, V> subRangeMap(Range<K> subRange) { if (subRange.equals(Range.all())) { return this; } else { return new SubRangeMap(subRange); } } @SuppressWarnings("unchecked") private RangeMap<K, V> emptySubRangeMap() { return EMPTY_SUB_RANGE_MAP; } private static final RangeMap EMPTY_SUB_RANGE_MAP = new RangeMap() { @Override @Nullable public Object get(Comparable key) { return null; } @Override @Nullable public Entry<Range, Object> getEntry(Comparable key) { return null; } @Override public Range span() { throw new NoSuchElementException(); } @Override public void put(Range range, Object value) { checkNotNull(range); throw new IllegalArgumentException( "Cannot insert range " + range + " into an empty subRangeMap"); } @Override public void putAll(RangeMap rangeMap) { if (!rangeMap.asMapOfRanges().isEmpty()) { throw new IllegalArgumentException( "Cannot putAll(nonEmptyRangeMap) into an empty " + "subRangeMap"); } } @Override public void clear() {} @Override public void remove(Range range) { checkNotNull(range); } @Override public Map<Range, Object> asMapOfRanges() { return Collections.emptyMap(); } @Override public RangeMap subRangeMap(Range range) { checkNotNull(range); return this; } }; private class SubRangeMap implements RangeMap<K, V> { private final Range<K> subRange; SubRangeMap(Range<K> subRange) { this.subRange = subRange; } @Override @Nullable public V get(K key) { return subRange.contains(key) ? TreeRangeMap.this.get(key) : null; } @Override @Nullable public Entry<Range<K>, V> getEntry(K key) { if (subRange.contains(key)) { Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key); if (entry != null) { return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); } } return null; } @Override public Range<K> span() { Cut<K> lowerBound; Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry = entriesByLowerBound.floorEntry(subRange.lowerBound); if (lowerEntry != null && lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) { lowerBound = subRange.lowerBound; } else { lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound); if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) { throw new NoSuchElementException(); } } Cut<K> upperBound; Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry = entriesByLowerBound.lowerEntry(subRange.upperBound); if (upperEntry == null) { throw new NoSuchElementException(); } else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) { upperBound = subRange.upperBound; } else { upperBound = upperEntry.getValue().getUpperBound(); } return Range.create(lowerBound, upperBound); } @Override public void put(Range<K> range, V value) { checkArgument(subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange); TreeRangeMap.this.put(range, value); } @Override public void putAll(RangeMap<K, V> rangeMap) { if (rangeMap.asMapOfRanges().isEmpty()) { return; } Range<K> span = rangeMap.span(); checkArgument(subRange.encloses(span), "Cannot putAll rangeMap with span %s into a subRangeMap(%s)", span, subRange); TreeRangeMap.this.putAll(rangeMap); } @Override public void clear() { TreeRangeMap.this.remove(subRange); } @Override public void remove(Range<K> range) { if (range.isConnected(subRange)) { TreeRangeMap.this.remove(range.intersection(subRange)); } } @Override public RangeMap<K, V> subRangeMap(Range<K> range) { if (!range.isConnected(subRange)) { return emptySubRangeMap(); } else { return TreeRangeMap.this.subRangeMap(range.intersection(subRange)); } } @Override public Map<Range<K>, V> asMapOfRanges() { return new SubRangeMapAsMap(); } @Override public boolean equals(@Nullable Object o) { if (o instanceof RangeMap) { RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; return asMapOfRanges().equals(rangeMap.asMapOfRanges()); } return false; } @Override public int hashCode() { return asMapOfRanges().hashCode(); } @Override public String toString() { return asMapOfRanges().toString(); } class SubRangeMapAsMap extends AbstractMap<Range<K>, V> { @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public V get(Object key) { try { if (key instanceof Range) { @SuppressWarnings("unchecked") // we catch ClassCastExceptions Range<K> r = (Range<K>) key; if (!subRange.encloses(r) || r.isEmpty()) { return null; } RangeMapEntry<K, V> candidate = null; if (r.lowerBound.compareTo(subRange.lowerBound) == 0) { // r could be truncated on the left Entry<Cut<K>, RangeMapEntry<K, V>> entry = entriesByLowerBound.floorEntry(r.lowerBound); if (entry != null) { candidate = entry.getValue(); } } else { candidate = entriesByLowerBound.get(r.lowerBound); } if (candidate != null && candidate.getKey().isConnected(subRange) && candidate.getKey().intersection(subRange).equals(r)) { return candidate.getValue(); } } } catch (ClassCastException e) { return null; } return null; } @Override public V remove(Object key) { V value = get(key); if (value != null) { @SuppressWarnings("unchecked") // it's definitely in the map, so safe Range<K> range = (Range<K>) key; TreeRangeMap.this.remove(range); return value; } return null; } @Override public void clear() { SubRangeMap.this.clear(); } private boolean removeIf(Predicate<? super Entry<Range<K>, V>> predicate) { List<Range<K>> toRemove = Lists.newArrayList(); for (Entry<Range<K>, V> entry : entrySet()) { if (predicate.apply(entry)) { toRemove.add(entry.getKey()); } } for (Range<K> range : toRemove) { TreeRangeMap.this.remove(range); } return !toRemove.isEmpty(); } @Override public Set<Range<K>> keySet() { return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) { @Override public boolean remove(@Nullable Object o) { return SubRangeMapAsMap.this.remove(o) != null; } @Override public boolean retainAll(Collection<?> c) { return removeIf(compose(not(in(c)), Maps.<Range<K>>keyFunction())); } }; } @Override public Set<Entry<Range<K>, V>> entrySet() { return new Maps.EntrySet<Range<K>, V>() { @Override Map<Range<K>, V> map() { return SubRangeMapAsMap.this; } @Override public Iterator<Entry<Range<K>, V>> iterator() { if (subRange.isEmpty()) { return Iterators.emptyIterator(); } Cut<K> cutToStart = Objects.firstNonNull( entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound); final Iterator<RangeMapEntry<K, V>> backingItr = entriesByLowerBound.tailMap(cutToStart, true).values().iterator(); return new AbstractIterator<Entry<Range<K>, V>>() { @Override protected Entry<Range<K>, V> computeNext() { while (backingItr.hasNext()) { RangeMapEntry<K, V> entry = backingItr.next(); if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) { break; } else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) { // this might not be true e.g. at the start of the iteration return Maps.immutableEntry( entry.getKey().intersection(subRange), entry.getValue()); } } return endOfData(); } }; } @Override public boolean retainAll(Collection<?> c) { return removeIf(not(in(c))); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return !iterator().hasNext(); } }; } @Override public Collection<V> values() { return new Maps.Values<Range<K>, V>(this) { @Override public boolean removeAll(Collection<?> c) { return removeIf(compose(in(c), Maps.<V>valueFunction())); } @Override public boolean retainAll(Collection<?> c) { return removeIf(compose(not(in(c)), Maps.<V>valueFunction())); } }; } } } @Override public boolean equals(@Nullable Object o) { if (o instanceof RangeMap) { RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; return asMapOfRanges().equals(rangeMap.asMapOfRanges()); } return false; } @Override public int hashCode() { return asMapOfRanges().hashCode(); } @Override public String toString() { return entriesByLowerBound.values().toString(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtIncompatible; import javax.annotation.Nullable; /** * Skeletal implementation of {@link ImmutableSortedSet#descendingSet()}. * * @author Louis Wasserman */ class DescendingImmutableSortedSet<E> extends ImmutableSortedSet<E> { private final ImmutableSortedSet<E> forward; DescendingImmutableSortedSet(ImmutableSortedSet<E> forward) { super(Ordering.from(forward.comparator()).reverse()); this.forward = forward; } @Override public int size() { return forward.size(); } @Override public UnmodifiableIterator<E> iterator() { return forward.descendingIterator(); } @Override ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) { return forward.tailSet(toElement, inclusive).descendingSet(); } @Override ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); } @Override ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) { return forward.headSet(fromElement, inclusive).descendingSet(); } @Override @GwtIncompatible("NavigableSet") public ImmutableSortedSet<E> descendingSet() { return forward; } @Override @GwtIncompatible("NavigableSet") public UnmodifiableIterator<E> descendingIterator() { return forward.iterator(); } @Override @GwtIncompatible("NavigableSet") ImmutableSortedSet<E> createDescendingSet() { throw new AssertionError("should never be called"); } @Override public E lower(E element) { return forward.higher(element); } @Override public E floor(E element) { return forward.ceiling(element); } @Override public E ceiling(E element) { return forward.floor(element); } @Override public E higher(E element) { return forward.lower(element); } @Override int indexOf(@Nullable Object target) { int index = forward.indexOf(target); if (index == -1) { return index; } else { return size() - 1 - index; } } @Override boolean isPartialView() { return forward.isPartialView(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.Map.Entry; import java.util.Set; /** * Implementation of {@link Multimaps#filterEntries(SetMultimap, Predicate)}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredEntrySetMultimap<K, V> extends FilteredEntryMultimap<K, V> implements FilteredSetMultimap<K, V> { FilteredEntrySetMultimap(SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { super(unfiltered, predicate); } @Override public SetMultimap<K, V> unfiltered() { return (SetMultimap<K, V>) unfiltered; } @Override public Set<V> get(K key) { return (Set<V>) super.get(key); } @Override public Set<V> removeAll(Object key) { return (Set<V>) super.removeAll(key); } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { return (Set<V>) super.replaceValues(key, values); } @Override Set<Entry<K, V>> createEntries() { return Sets.filter(unfiltered().entries(), entryPredicate()); } @Override public Set<Entry<K, V>> entries() { return (Set<Entry<K, V>>) super.entries(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableMap<K, V> { private ForwardingImmutableMap() {} }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; /** * An {@link ImmutableAsList} implementation specialized for when the delegate collection is * already backed by an {@code ImmutableList} or array. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization class RegularImmutableAsList<E> extends ImmutableAsList<E> { private final ImmutableCollection<E> delegate; private final ImmutableList<? extends E> delegateList; RegularImmutableAsList(ImmutableCollection<E> delegate, ImmutableList<? extends E> delegateList) { this.delegate = delegate; this.delegateList = delegateList; } RegularImmutableAsList(ImmutableCollection<E> delegate, Object[] array) { this(delegate, ImmutableList.<E>asImmutableList(array)); } @Override ImmutableCollection<E> delegateCollection() { return delegate; } ImmutableList<? extends E> delegateList() { return delegateList; } @SuppressWarnings("unchecked") // safe covariant cast! @Override public UnmodifiableListIterator<E> listIterator(int index) { return (UnmodifiableListIterator<E>) delegateList.listIterator(index); } @GwtIncompatible("not present in emulated superclass") @Override int copyIntoArray(Object[] dst, int offset) { return delegateList.copyIntoArray(dst, offset); } @Override public E get(int index) { return delegateList.get(index); } }
Java
/* * Copyright (C) 2012 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 static com.google.common.base.Preconditions.checkPositionIndex; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@link Multimaps#filterKeys(Multimap, Predicate)}. * * @author Louis Wasserman */ @GwtCompatible class FilteredKeyMultimap<K, V> extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> { final Multimap<K, V> unfiltered; final Predicate<? super K> keyPredicate; FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) { this.unfiltered = checkNotNull(unfiltered); this.keyPredicate = checkNotNull(keyPredicate); } @Override public Multimap<K, V> unfiltered() { return unfiltered; } @Override public Predicate<? super Entry<K, V>> entryPredicate() { return Maps.keyPredicateOnEntries(keyPredicate); } @Override public int size() { int size = 0; for (Collection<V> collection : asMap().values()) { size += collection.size(); } return size; } @Override public boolean containsKey(@Nullable Object key) { if (unfiltered.containsKey(key)) { @SuppressWarnings("unchecked") // k is equal to a K, if not one itself K k = (K) key; return keyPredicate.apply(k); } return false; } @Override public Collection<V> removeAll(Object key) { return containsKey(key) ? unfiltered.removeAll(key) : unmodifiableEmptyCollection(); } Collection<V> unmodifiableEmptyCollection() { if (unfiltered instanceof SetMultimap) { return ImmutableSet.of(); } else { return ImmutableList.of(); } } @Override public void clear() { keySet().clear(); } @Override Set<K> createKeySet() { return Sets.filter(unfiltered.keySet(), keyPredicate); } @Override public Collection<V> get(K key) { if (keyPredicate.apply(key)) { return unfiltered.get(key); } else if (unfiltered instanceof SetMultimap) { return new AddRejectingSet<K, V>(key); } else { return new AddRejectingList<K, V>(key); } } static class AddRejectingSet<K, V> extends ForwardingSet<V> { final K key; AddRejectingSet(K key) { this.key = key; } @Override public boolean add(V element) { throw new IllegalArgumentException("Key does not satisfy predicate: " + key); } @Override public boolean addAll(Collection<? extends V> collection) { checkNotNull(collection); throw new IllegalArgumentException("Key does not satisfy predicate: " + key); } @Override protected Set<V> delegate() { return Collections.emptySet(); } } static class AddRejectingList<K, V> extends ForwardingList<V> { final K key; AddRejectingList(K key) { this.key = key; } @Override public boolean add(V v) { add(0, v); return true; } @Override public boolean addAll(Collection<? extends V> collection) { addAll(0, collection); return true; } @Override public void add(int index, V element) { checkPositionIndex(index, 0); throw new IllegalArgumentException("Key does not satisfy predicate: " + key); } @Override public boolean addAll(int index, Collection<? extends V> elements) { checkNotNull(elements); checkPositionIndex(index, 0); throw new IllegalArgumentException("Key does not satisfy predicate: " + key); } @Override protected List<V> delegate() { return Collections.emptyList(); } } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Collection<Entry<K, V>> createEntries() { return new Entries(); } class Entries extends ForwardingCollection<Entry<K, V>> { @Override protected Collection<Entry<K, V>> delegate() { return Collections2.filter(unfiltered.entries(), entryPredicate()); } @Override @SuppressWarnings("unchecked") public boolean remove(@Nullable Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; if (unfiltered.containsKey(entry.getKey()) // if this holds, then we know entry.getKey() is a K && keyPredicate.apply((K) entry.getKey())) { return unfiltered.remove(entry.getKey(), entry.getValue()); } } return false; } } @Override Collection<V> createValues() { return new FilteredMultimapValues<K, V>(this); } @Override Map<K, Collection<V>> createAsMap() { return Maps.filterKeys(unfiltered.asMap(), keyPredicate); } @Override Multiset<K> createKeys() { return Multisets.filter(unfiltered.keys(), keyPredicate); } }
Java
/* * Copyright (C) 2011 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; /** * A {@link Multiset} which maintains the ordering of its elements, according to * either their natural order or an explicit {@link Comparator}. In all cases, * this implementation uses {@link Comparable#compareTo} or * {@link Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as * explained by the {@link Comparable} class specification. Otherwise, the * resulting multiset will violate the {@link Collection} contract, which it is * specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Louis Wasserman * @since 11.0 */ @Beta @GwtCompatible(emulated = true) public interface SortedMultiset<E> extends SortedMultisetBridge<E>, SortedIterable<E> { /** * Returns the comparator that orders this multiset, or * {@link Ordering#natural()} if the natural ordering of the elements is used. */ Comparator<? super E> comparator(); /** * Returns the entry of the first element in this multiset, or {@code null} if * this multiset is empty. */ Entry<E> firstEntry(); /** * Returns the entry of the last element in this multiset, or {@code null} if * this multiset is empty. */ Entry<E> lastEntry(); /** * Returns and removes the entry associated with the lowest element in this * multiset, or returns {@code null} if this multiset is empty. */ Entry<E> pollFirstEntry(); /** * Returns and removes the entry associated with the greatest element in this * multiset, or returns {@code null} if this multiset is empty. */ Entry<E> pollLastEntry(); /** * Returns a {@link NavigableSet} view of the distinct elements in this multiset. * * @since 14.0 (present with return type {@code SortedSet} since 11.0) */ @Override NavigableSet<E> elementSet(); /** * {@inheritDoc} * * <p>The iterator returns the elements in ascending order according to this * multiset's comparator. */ @Override Iterator<E> iterator(); /** * Returns a descending view of this multiset. Modifications made to either * map will be reflected in the other. */ SortedMultiset<E> descendingMultiset(); /** * Returns a view of this multiset restricted to the elements less than * {@code upperBound}, optionally including {@code upperBound} itself. The * returned multiset is a view of this multiset, so changes to one will be * reflected in the other. The returned multiset supports all operations that * this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. */ SortedMultiset<E> headMultiset(E upperBound, BoundType boundType); /** * Returns a view of this multiset restricted to the range between * {@code lowerBound} and {@code upperBound}. The returned multiset is a view * of this multiset, so changes to one will be reflected in the other. The * returned multiset supports all operations that this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. * * <p>This method is equivalent to * {@code tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, * upperBoundType)}. */ SortedMultiset<E> subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType); /** * Returns a view of this multiset restricted to the elements greater than * {@code lowerBound}, optionally including {@code lowerBound} itself. The * returned multiset is a view of this multiset, so changes to one will be * reflected in the other. The returned multiset supports all operations that * this multiset supports. * * <p>The returned multiset will throw an {@link IllegalArgumentException} on * attempts to add elements outside its range. */ SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType); }
Java
/* * 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.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Set; import javax.annotation.Nullable; /** * A set which forwards all its method calls to another set. Subclasses should * override one or more methods to modify the behavior of the backing set as * desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingSet} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} method. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSet<E> extends ForwardingCollection<E> implements Set<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingSet() {} @Override protected abstract Set<E> delegate(); @Override public boolean equals(@Nullable Object object) { return object == this || delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible definition of {@link #removeAll} in terms of {@link #iterator} * and {@link #remove}. If you override {@code iterator} or {@code remove}, * you may wish to override {@link #removeAll} to forward to this * implementation. * * @since 7.0 (this version overrides the {@code ForwardingCollection} version as of 12.0) */ @Override protected boolean standardRemoveAll(Collection<?> collection) { return Sets.removeAllImpl(this, checkNotNull(collection)); // for GWT } /** * A sensible definition of {@link #equals} in terms of {@link #size} and * {@link #containsAll}. If you override either of those methods, you may wish * to override {@link #equals} to forward to this implementation. * * @since 7.0 */ protected boolean standardEquals(@Nullable Object object) { return Sets.equalsImpl(this, object); } /** * A sensible definition of {@link #hashCode} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link #equals} * to forward to this implementation. * * @since 7.0 */ protected int standardHashCode() { return Sets.hashCodeImpl(this); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A {@code Multimap} that cannot hold duplicate key-value pairs. Adding a * key-value pair that's already in the multimap has no effect. See the {@link * Multimap} documentation for information common to all multimaps. * * <p>The {@link #get}, {@link #removeAll}, and {@link #replaceValues} methods * each return a {@link Set} of values, while {@link #entries} returns a {@code * Set} of map entries. Though the method signature doesn't say so explicitly, * the map returned by {@link #asMap} has {@code Set} values. * * <p>If the values corresponding to a single key should be ordered according to * a {@link java.util.Comparator} (or the natural order), see the * {@link SortedSetMultimap} subinterface. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface SetMultimap<K, V> extends Multimap<K, V> { /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<V> get(@Nullable K key); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<V> removeAll(@Nullable Object key); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. * * <p>Any duplicates in {@code values} will be stored in the multimap once. */ @Override Set<V> replaceValues(K key, Iterable<? extends V> values); /** * {@inheritDoc} * * <p>Because a {@code SetMultimap} has unique values for a given key, this * method returns a {@link Set}, instead of the {@link java.util.Collection} * specified in the {@link Multimap} interface. */ @Override Set<Map.Entry<K, V>> entries(); /** * {@inheritDoc} * * <p><b>Note:</b> The returned map's values are guaranteed to be of type * {@link Set}. To obtain this map with the more specific generic type * {@code Map<K, Set<V>>}, call {@link Multimaps#asMap(SetMultimap)} instead. */ @Override Map<K, Collection<V>> asMap(); /** * Compares the specified object to this multimap for equality. * * <p>Two {@code SetMultimap} instances are equal if, for each key, they * contain the same values. Equality does not depend on the ordering of keys * or values. * * <p>An empty {@code SetMultimap} is equal to any other empty {@code * Multimap}, including an empty {@code ListMultimap}. */ @Override boolean equals(@Nullable Object obj); }
Java
/* * 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.ObjectArrays.checkElementNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * A high-performance, immutable {@code Set} with reliable, user-specified * iteration order. Does not permit null elements. * * <p>Unlike {@link Collections#unmodifiableSet}, which is a <i>view</i> of a * separate collection that can still change, an instance of this class contains * its own private data and will <i>never</i> change. This class is convenient * for {@code public static final} sets ("constant sets") and also lets you * easily make a "defensive copy" of a set provided to your class by a caller. * * <p><b>Warning:</b> Like most sets, an {@code ImmutableSet} will not function * correctly if an element is modified after being placed in the set. For this * reason, and to avoid general confusion, it is strongly recommended to place * only immutable objects into this collection. * * <p>This class has been observed to perform significantly better than {@link * HashSet} for objects with very fast {@link Object#hashCode} implementations * (as a well-behaved immutable object should). While this class's factory * methods create hash-based instances, the {@link ImmutableSortedSet} subclass * performs binary searches instead. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed * outside its package as it has no public or protected constructors. Thus, * instances of this type are guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @see ImmutableList * @see ImmutableMap * @author Kevin Bourrillion * @author Nick Kralevich * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> { /** * Returns the empty immutable set. This set behaves and performs comparably * to {@link Collections#emptySet}, and is preferable mainly for consistency * and maintainability of your code. */ // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings({"unchecked"}) public static <E> ImmutableSet<E> of() { return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE; } /** * Returns an immutable set containing a single element. This set behaves and * performs comparably to {@link Collections#singleton}, but will not accept * a null element. It is preferable mainly for consistency and * maintainability of your code. */ public static <E> ImmutableSet<E> of(E element) { return new SingletonImmutableSet<E>(element); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2) { return construct(2, e1, e2); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { return construct(3, e1, e2, e3); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { return construct(4, e1, e2, e3, e4); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { return construct(5, e1, e2, e3, e4, e5); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { final int paramCount = 6; Object[] elements = new Object[paramCount + others.length]; elements[0] = e1; elements[1] = e2; elements[2] = e3; elements[3] = e4; elements[4] = e5; elements[5] = e6; System.arraycopy(others, 0, elements, paramCount, others.length); return construct(elements.length, elements); } /** * Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array. * If {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of * {@code elements} will be in the first {@code k} positions, and {@code elements[i] == null} for * {@code k <= i < n}. * * <p>This may modify {@code elements}. Additionally, if {@code n == elements.length} and * {@code elements} contains no duplicates, {@code elements} may be used without copying in the * returned {@code ImmutableSet}, in which case it may no longer be modified. * * <p>{@code elements} may contain only values of type {@code E}. * * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is * null */ private static <E> ImmutableSet<E> construct(int n, Object... elements) { switch (n) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // safe; elements contains only E's E elem = (E) elements[0]; return of(elem); default: // continue below to handle the general case } int tableSize = chooseTableSize(n); Object[] table = new Object[tableSize]; int mask = tableSize - 1; int hashCode = 0; int uniques = 0; for (int i = 0; i < n; i++) { Object element = checkElementNotNull(elements[i], i); int hash = element.hashCode(); for (int j = Hashing.smear(hash); ; j++) { int index = j & mask; Object value = table[index]; if (value == null) { // Came to an empty slot. Put the element here. elements[uniques++] = element; table[index] = element; hashCode += hash; break; } else if (value.equals(element)) { break; } } } Arrays.fill(elements, uniques, n, null); if (uniques == 1) { // There is only one element or elements are all duplicates @SuppressWarnings("unchecked") // we are careful to only pass in E E element = (E) elements[0]; return new SingletonImmutableSet<E>(element, hashCode); } else if (tableSize != chooseTableSize(uniques)) { // Resize the table when the array includes too many duplicates. // when this happens, we have already made a copy return construct(uniques, elements); } else { Object[] uniqueElements = (uniques < elements.length) ? ObjectArrays.arraysCopyOf(elements, uniques) : elements; return new RegularImmutableSet<E>(uniqueElements, hashCode, table, mask); } } // We use power-of-2 tables, and this is the highest int that's a power of 2 static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; // Represents how tightly we can pack things, as a maximum. private static final double DESIRED_LOAD_FACTOR = 0.7; // If the set has this many elements, it will "max out" the table size private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); /** * Returns an array size suitable for the backing array of a hash table that * uses open addressing with linear probing in its implementation. The * returned size is the smallest power of two that can hold setSize elements * with the desired load factor. * * <p>Do not call this method with setSize < 2. */ @VisibleForTesting static int chooseTableSize(int setSize) { // Correct the size for open addressing to match desired load factor. if (setSize < CUTOFF) { // Round up to the next highest power of 2. int tableSize = Integer.highestOneBit(setSize - 1) << 1; while (tableSize * DESIRED_LOAD_FACTOR < setSize) { tableSize <<= 1; } return tableSize; } // The table can't be completely full or we'll get infinite reprobes checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); return MAX_TABLE_SIZE; } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E> ImmutableSet<E> copyOf(E[] elements) { switch (elements.length) { case 0: return of(); case 1: return of(elements[0]); default: return construct(elements.length, elements.clone()); } } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <p>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. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { // We special-case for 0 or 1 elements, but anything further is madness. if (!elements.hasNext()) { return of(); } E first = elements.next(); if (!elements.hasNext()) { return of(first); } else { return new ImmutableSet.Builder<E>() .add(first) .addAll(elements) .build(); } } /** * Returns an immutable set containing the given elements, in order. Repeated * occurrences of an element (according to {@link Object#equals}) after the * first are ignored. This method iterates over {@code elements} at most * once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet<String>} containing * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns * a {@code ImmutableSet<Set<String>>} containing one element (the given set * itself). * * <p><b>Note:</b> Despite what the method name suggests, {@code copyOf} will * return constant-space views, rather than linear-space copies, of some * inputs known to be immutable. For some other immutable inputs, such as key * sets of an {@code ImmutableMap}, it still performs a copy in order to avoid * holding references to the values of the map. The heuristics used in this * decision are undocumented and subject to change except that: * <ul> * <li>A full copy will be done of any {@code ImmutableSortedSet}.</li> * <li>{@code ImmutableSet.copyOf()} is idempotent with respect to pointer * equality.</li> * </ul> * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if any of {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { /* * TODO(user): consider checking for ImmutableAsList here * TODO(user): consider checking for Multiset here */ if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; if (!set.isPartialView()) { return set; } } else if (elements instanceof EnumSet) { EnumSet<?> enumSet = EnumSet.copyOf((EnumSet<?>) elements); @SuppressWarnings("unchecked") // immutable collections are safe for covariant casts ImmutableSet<E> result = (ImmutableSet<E>) ImmutableEnumSet.asImmutable(enumSet); return result; } Object[] array = elements.toArray(); return construct(array.length, array); } ImmutableSet() {} /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ boolean isHashCodeFast() { return false; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } else if (object instanceof ImmutableSet && isHashCodeFast() && ((ImmutableSet<?>) object).isHashCodeFast() && hashCode() != object.hashCode()) { return false; } return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } // This declaration is needed to make Set.iterator() and // ImmutableCollection.iterator() consistent. @Override public abstract UnmodifiableIterator<E> iterator(); /* * This class is used to serialize all ImmutableSet instances, except for * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It * captures their "logical contents" and they are reconstructed using public * static factories. This is necessary to ensure that the existence of a * particular implementation type is an implementation detail. */ private static class SerializedForm implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return copyOf(elements); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(toArray()); } /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <E> Builder<E> builder() { return new Builder<E>(); } /** * A builder for creating immutable set instances, especially {@code public * static final} sets ("constant sets"). Example: <pre> {@code * * public static final ImmutableSet<Color> GOOGLE_COLORS = * new ImmutableSet.Builder<Color>() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple sets in series. Each set is a superset of the set * created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSet#builder}. */ public Builder() { this(DEFAULT_INITIAL_CAPACITY); } Builder(int capacity) { super(capacity); } /** * Adds {@code element} to the {@code ImmutableSet}. If the {@code * ImmutableSet} already contains {@code element}, then {@code add} has no * effect (only the previously added element is retained). * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the {@code Iterable} to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add to the {@code ImmutableSet} * @return this {@code Builder} object * @throws NullPointerException if {@code 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 {@code ImmutableSet} based on the contents of * the {@code Builder}. */ @Override public ImmutableSet<E> build() { ImmutableSet<E> result = construct(size, contents); // construct has the side effect of deduping contents, so we update size // accordingly. size = result.size(); return result; } } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; import java.util.Queue; /** * Views elements of a type {@code T} as nodes in a tree, and provides methods to traverse the trees * induced by this traverser. * * <p>For example, the tree * * <pre> {@code * h * / | \ * / e \ * d g * /|\ | * / | \ f * a b c }</pre> * * <p>can be iterated over in preorder (hdabcegf), postorder (abcdefgh), or breadth-first order * (hdegabc). * * <p>Null nodes are strictly forbidden. * * @author Louis Wasserman * @since 15.0 */ @Beta @GwtCompatible(emulated = true) public abstract class TreeTraverser<T> { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque emulation /** * Returns the children of the specified node. Must not contain null. */ public abstract Iterable<T> children(T root); /** * Returns an unmodifiable iterable over the nodes in a tree structure, using pre-order * traversal. That is, each node's subtrees are traversed after the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return preOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> preOrderIterator(T root) { return new PreOrderIterator(root); } private final class PreOrderIterator extends UnmodifiableIterator<T> { private final Deque<Iterator<T>> stack; PreOrderIterator(T root) { this.stack = new ArrayDeque<Iterator<T>>(); stack.addLast(Iterators.singletonIterator(checkNotNull(root))); } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { Iterator<T> itr = stack.getLast(); // throws NSEE if empty T result = checkNotNull(itr.next()); if (!itr.hasNext()) { stack.removeLast(); } Iterator<T> childItr = children(result).iterator(); if (childItr.hasNext()) { stack.addLast(childItr); } return result; } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using post-order * traversal. That is, each node's subtrees are traversed before the node itself is returned. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> postOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return postOrderIterator(root); } }; } // overridden in BinaryTreeTraverser UnmodifiableIterator<T> postOrderIterator(T root) { return new PostOrderIterator(root); } private static final class PostOrderNode<T> { final T root; final Iterator<T> childIterator; PostOrderNode(T root, Iterator<T> childIterator) { this.root = checkNotNull(root); this.childIterator = checkNotNull(childIterator); } } private final class PostOrderIterator extends AbstractIterator<T> { private final ArrayDeque<PostOrderNode<T>> stack; PostOrderIterator(T root) { this.stack = new ArrayDeque<PostOrderNode<T>>(); stack.addLast(expand(root)); } @Override protected T computeNext() { while (!stack.isEmpty()) { PostOrderNode<T> top = stack.getLast(); if (top.childIterator.hasNext()) { T child = top.childIterator.next(); stack.addLast(expand(child)); } else { stack.removeLast(); return top.root; } } return endOfData(); } private PostOrderNode<T> expand(T t) { return new PostOrderNode<T>(t, children(t).iterator()); } } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using breadth-first * traversal. That is, all the nodes of depth 0 are returned, then depth 1, then 2, and so on. * * <p>No guarantees are made about the behavior of the traversal when nodes change while * iteration is in progress or when the iterators generated by {@link #children} are advanced. */ public final FluentIterable<T> breadthFirstTraversal(final T root) { checkNotNull(root); return new FluentIterable<T>() { @Override public UnmodifiableIterator<T> iterator() { return new BreadthFirstIterator(root); } }; } private final class BreadthFirstIterator extends UnmodifiableIterator<T> implements PeekingIterator<T> { private final Queue<T> queue; BreadthFirstIterator(T root) { this.queue = new ArrayDeque<T>(); queue.add(root); } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T peek() { return queue.element(); } @Override public T next() { T result = queue.remove(); Iterables.addAll(queue, children(result)); return result; } } }
Java
/* * 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.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.collect.MapMakerInternalMap.ReferenceEntry; import java.util.concurrent.ConcurrentMap; /** * Contains static methods pertaining to instances of {@link Interner}. * * @author Kevin Bourrillion * @since 3.0 */ @Beta public final class Interners { private Interners() {} /** * Returns a new thread-safe interner which retains a strong reference to each instance it has * interned, thus preventing these instances from being garbage-collected. If this retention is * acceptable, this implementation may perform better than {@link #newWeakInterner}. Note that * unlike {@link String#intern}, using this interner does not consume memory in the permanent * generation. */ public static <E> Interner<E> newStrongInterner() { final ConcurrentMap<E, E> map = new MapMaker().makeMap(); return new Interner<E>() { @Override public E intern(E sample) { E canonical = map.putIfAbsent(checkNotNull(sample), sample); return (canonical == null) ? sample : canonical; } }; } /** * Returns a new thread-safe interner which retains a weak reference to each instance it has * interned, and so does not prevent these instances from being garbage-collected. This most * likely does not perform as well as {@link #newStrongInterner}, but is the best alternative * when the memory usage of that implementation is unacceptable. Note that unlike {@link * String#intern}, using this interner does not consume memory in the permanent generation. */ @GwtIncompatible("java.lang.ref.WeakReference") public static <E> Interner<E> newWeakInterner() { return new WeakInterner<E>(); } private static class WeakInterner<E> implements Interner<E> { // MapMaker is our friend, we know about this type private final MapMakerInternalMap<E, Dummy> map = new MapMaker() .weakKeys() .keyEquivalence(Equivalence.equals()) .makeCustomMap(); @Override public E intern(E sample) { while (true) { // trying to read the canonical... ReferenceEntry<E, Dummy> entry = map.getEntry(sample); if (entry != null) { E canonical = entry.getKey(); if (canonical != null) { // only matters if weak/soft keys are used return canonical; } } // didn't see it, trying to put it instead... Dummy sneaky = map.putIfAbsent(sample, Dummy.VALUE); if (sneaky == null) { return sample; } else { /* Someone beat us to it! Trying again... * * Technically this loop not guaranteed to terminate, so theoretically (extremely * unlikely) this thread might starve, but even then, there is always going to be another * thread doing progress here. */ } } } private enum Dummy { VALUE } } /** * Returns a function that delegates to the {@link Interner#intern} method of the given interner. * * @since 8.0 */ public static <E> Function<E, E> asFunction(Interner<E> interner) { return new InternerFunction<E>(checkNotNull(interner)); } private static class InternerFunction<E> implements Function<E, E> { private final Interner<E> interner; public InternerFunction(Interner<E> interner) { this.interner = interner; } @Override public E apply(E input) { return interner.intern(input); } @Override public int hashCode() { return interner.hashCode(); } @Override public boolean equals(Object other) { if (other instanceof InternerFunction) { InternerFunction<?> that = (InternerFunction<?>) other; return interner.equals(that.interner); } return false; } } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Multisets.UnmodifiableMultiset; import java.util.Comparator; import java.util.NavigableSet; /** * Implementation of {@link Multisets#unmodifiableSortedMultiset(SortedMultiset)}, * split out into its own file so it can be GWT emulated (to deal with the differing * elementSet() types in GWT and non-GWT). * * @author Louis Wasserman */ @GwtCompatible(emulated = true) final class UnmodifiableSortedMultiset<E> extends UnmodifiableMultiset<E> implements SortedMultiset<E> { UnmodifiableSortedMultiset(SortedMultiset<E> delegate) { super(delegate); } @Override protected SortedMultiset<E> delegate() { return (SortedMultiset<E>) super.delegate(); } @Override public Comparator<? super E> comparator() { return delegate().comparator(); } @Override NavigableSet<E> createElementSet() { return Sets.unmodifiableNavigableSet(delegate().elementSet()); } @Override public NavigableSet<E> elementSet() { return (NavigableSet<E>) super.elementSet(); } private transient UnmodifiableSortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { UnmodifiableSortedMultiset<E> result = descendingMultiset; if (result == null) { result = new UnmodifiableSortedMultiset<E>( delegate().descendingMultiset()); result.descendingMultiset = this; return descendingMultiset = result; } return result; } @Override public Entry<E> firstEntry() { return delegate().firstEntry(); } @Override public Entry<E> lastEntry() { return delegate().lastEntry(); } @Override public Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().headMultiset(upperBound, boundType)); } @Override public SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { return Multisets.unmodifiableSortedMultiset(delegate().subMultiset( lowerBound, lowerBoundType, upperBound, upperBoundType)); } @Override public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset( delegate().tailMultiset(lowerBound, boundType)); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 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 com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import javax.annotation.Nullable; /** * This class provides a skeletal implementation of the {@link SortedMultiset} interface. * * <p>The {@link #count} and {@link #size} implementations all iterate across the set returned by * {@link Multiset#entrySet()}, as do many methods acting on the set returned by * {@link #elementSet()}. Override those methods for better performance. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) abstract class AbstractSortedMultiset<E> extends AbstractMultiset<E> implements SortedMultiset<E> { @GwtTransient final Comparator<? super E> comparator; // needed for serialization @SuppressWarnings("unchecked") AbstractSortedMultiset() { this((Comparator) Ordering.natural()); } AbstractSortedMultiset(Comparator<? super E> comparator) { this.comparator = checkNotNull(comparator); } @Override public NavigableSet<E> elementSet() { return (NavigableSet<E>) super.elementSet(); } @Override NavigableSet<E> createElementSet() { return new SortedMultisets.NavigableElementSet<E>(this); } @Override public Comparator<? super E> comparator() { return comparator; } @Override public Entry<E> firstEntry() { Iterator<Entry<E>> entryIterator = entryIterator(); return entryIterator.hasNext() ? entryIterator.next() : null; } @Override public Entry<E> lastEntry() { Iterator<Entry<E>> entryIterator = descendingEntryIterator(); return entryIterator.hasNext() ? entryIterator.next() : null; } @Override public Entry<E> pollFirstEntry() { Iterator<Entry<E>> entryIterator = entryIterator(); if (entryIterator.hasNext()) { Entry<E> result = entryIterator.next(); result = Multisets.immutableEntry(result.getElement(), result.getCount()); entryIterator.remove(); return result; } return null; } @Override public Entry<E> pollLastEntry() { Iterator<Entry<E>> entryIterator = descendingEntryIterator(); if (entryIterator.hasNext()) { Entry<E> result = entryIterator.next(); result = Multisets.immutableEntry(result.getElement(), result.getCount()); entryIterator.remove(); return result; } return null; } @Override public SortedMultiset<E> subMultiset(@Nullable E fromElement, BoundType fromBoundType, @Nullable E toElement, BoundType toBoundType) { // These are checked elsewhere, but NullPointerTester wants them checked eagerly. checkNotNull(fromBoundType); checkNotNull(toBoundType); return tailMultiset(fromElement, fromBoundType).headMultiset(toElement, toBoundType); } abstract Iterator<Entry<E>> descendingEntryIterator(); Iterator<E> descendingIterator() { return Multisets.iteratorImpl(descendingMultiset()); } private transient SortedMultiset<E> descendingMultiset; @Override public SortedMultiset<E> descendingMultiset() { SortedMultiset<E> result = descendingMultiset; return (result == null) ? descendingMultiset = createDescendingMultiset() : result; } SortedMultiset<E> createDescendingMultiset() { return new DescendingMultiset<E>() { @Override SortedMultiset<E> forwardMultiset() { return AbstractSortedMultiset.this; } @Override Iterator<Entry<E>> entryIterator() { return descendingEntryIterator(); } @Override public Iterator<E> iterator() { return descendingIterator(); } }; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.LinkedHashMap; /** * A {@code Multiset} implementation with predictable iteration order. Its * iterator orders elements according to when the first occurrence of the * element was added. When the multiset contains multiple instances of an * element, those instances are consecutive in the iteration order. If all * occurrences of an element are removed, after which that element is added to * the multiset, the element will appear at the end of the iteration. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. */ public static <E> LinkedHashMultiset<E> create() { return new LinkedHashMultiset<E>(); } /** * Creates a new, empty {@code LinkedHashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> LinkedHashMultiset<E> create(int distinctElements) { return new LinkedHashMultiset<E>(distinctElements); } /** * Creates a new {@code LinkedHashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> LinkedHashMultiset<E> create( Iterable<? extends E> elements) { LinkedHashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private LinkedHashMultiset() { super(new LinkedHashMap<E, Count>()); } private LinkedHashMultiset(int distinctElements) { // Could use newLinkedHashMapWithExpectedSize() if it existed super(new LinkedHashMap<E, Count>(Maps.capacity(distinctElements))); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap(new LinkedHashMap<E, Count>( Maps.capacity(distinctElements))); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; /** * List returned by {@link ImmutableCollection#asList} that delegates {@code contains} checks * to the backing collection. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") abstract class ImmutableAsList<E> extends ImmutableList<E> { abstract ImmutableCollection<E> delegateCollection(); @Override public boolean contains(Object target) { // The collection's contains() is at least as fast as ImmutableList's // and is often faster. return delegateCollection().contains(target); } @Override public int size() { return delegateCollection().size(); } @Override public boolean isEmpty() { return delegateCollection().isEmpty(); } @Override boolean isPartialView() { return delegateCollection().isPartialView(); } /** * Serialized form that leads to the same performance as the original list. */ @GwtIncompatible("serialization") static class SerializedForm implements Serializable { final ImmutableCollection<?> collection; SerializedForm(ImmutableCollection<?> collection) { this.collection = collection; } Object readResolve() { return collection.asList(); } private static final long serialVersionUID = 0; } @GwtIncompatible("serialization") private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm(delegateCollection()); } }
Java
/* * Copyright (C) 2009 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.Objects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * An immutable {@link SetMultimap} with reliable user-specified key and value * iteration order. Does not permit null keys or values. * * <p>Unlike {@link Multimaps#unmodifiableSetMultimap(SetMultimap)}, which is * a <i>view</i> of a separate multimap which can still change, an instance of * {@code ImmutableSetMultimap} contains its own data and will <i>never</i> * change. {@code ImmutableSetMultimap} is convenient for * {@code public static final} multimaps ("constant multimaps") and also lets * you easily make a "defensive copy" of a multimap provided to your class by * a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class * are guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Mike Ward * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class ImmutableSetMultimap<K, V> extends ImmutableMultimap<K, V> implements SetMultimap<K, V> { /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableSetMultimap<K, V> of() { return (ImmutableSetMultimap<K, V>) EmptyImmutableSetMultimap.INSTANCE; } /** * Returns an immutable multimap containing a single entry. */ public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of(K k1, V v1, K k2, V v2) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); return builder.build(); } /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after * the first are ignored. */ public static <K, V> ImmutableSetMultimap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder(); builder.put(k1, v1); builder.put(k2, v2); builder.put(k3, v3); builder.put(k4, v4); builder.put(k5, v5); return builder.build(); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new {@link Builder}. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * Multimap for {@link ImmutableSetMultimap.Builder} that maintains key * and value orderings and performs better than {@link LinkedHashMultimap}. */ private static class BuilderMultimap<K, V> extends AbstractMapBasedMultimap<K, V> { BuilderMultimap() { super(new LinkedHashMap<K, Collection<V>>()); } @Override Collection<V> createCollection() { return Sets.newLinkedHashSet(); } private static final long serialVersionUID = 0; } /** * A builder for creating immutable {@code SetMultimap} instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: * <pre> {@code * * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP = * new ImmutableSetMultimap.Builder<String, Integer>() * .put("one", 1) * .putAll("several", 1, 2, 3) * .putAll("many", 1, 2, 3, 4, 5) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple multimaps in series. Each multimap contains the * key-value mappings in the previously created multimaps. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<K, V> extends ImmutableMultimap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSetMultimap#builder}. */ public Builder() { builderMultimap = new BuilderMultimap<K, V>(); } /** * Adds a key-value mapping to the built multimap if it is not already * present. */ @Override public Builder<K, V> put(K key, V value) { builderMultimap.put(checkNotNull(key), checkNotNull(value)); return this; } /** * Adds an entry to the built multimap if it is not already present. * * @since 11.0 */ @Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { builderMultimap.put( checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); return this; } @Override public Builder<K, V> putAll(K key, Iterable<? extends V> values) { Collection<V> collection = builderMultimap.get(checkNotNull(key)); for (V value : values) { collection.add(checkNotNull(value)); } return this; } @Override public Builder<K, V> putAll(K key, V... values) { return putAll(key, Arrays.asList(values)); } @Override public Builder<K, V> putAll( Multimap<? extends K, ? extends V> multimap) { for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { putAll(entry.getKey(), entry.getValue()); } return this; } /** * {@inheritDoc} * * @since 8.0 */ @Override public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) { this.keyComparator = checkNotNull(keyComparator); return this; } /** * Specifies the ordering of the generated multimap's values for each key. * * <p>If this method is called, the sets returned by the {@code get()} * method of the generated multimap and its {@link Multimap#asMap()} view * are {@link ImmutableSortedSet} instances. However, serialization does not * preserve that property, though it does maintain the key and value * ordering. * * @since 8.0 */ // TODO: Make serialization behavior consistent. @Override public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) { super.orderValuesBy(valueComparator); return this; } /** * Returns a newly-created immutable set multimap. */ @Override public ImmutableSetMultimap<K, V> build() { if (keyComparator != null) { Multimap<K, V> sortedCopy = new BuilderMultimap<K, V>(); List<Map.Entry<K, Collection<V>>> entries = Lists.newArrayList( builderMultimap.asMap().entrySet()); Collections.sort( entries, Ordering.from(keyComparator).<K>onKeys()); for (Map.Entry<K, Collection<V>> entry : entries) { sortedCopy.putAll(entry.getKey(), entry.getValue()); } builderMultimap = sortedCopy; } return copyOf(builderMultimap, valueComparator); } } /** * Returns an immutable set multimap containing the same mappings as * {@code multimap}. The generated multimap's key and value orderings * correspond to the iteration ordering of the {@code multimap.asMap()} view. * Repeated occurrences of an entry in the multimap after the first are * ignored. * * <p>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. * * @throws NullPointerException if any key or value in {@code multimap} is * null */ public static <K, V> ImmutableSetMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap) { return copyOf(multimap, null); } private static <K, V> ImmutableSetMultimap<K, V> copyOf( Multimap<? extends K, ? extends V> multimap, Comparator<? super V> valueComparator) { checkNotNull(multimap); // eager for GWT if (multimap.isEmpty() && valueComparator == null) { return of(); } if (multimap instanceof ImmutableSetMultimap) { @SuppressWarnings("unchecked") // safe since multimap is not writable ImmutableSetMultimap<K, V> kvMultimap = (ImmutableSetMultimap<K, V>) multimap; if (!kvMultimap.isPartialView()) { return kvMultimap; } } ImmutableMap.Builder<K, ImmutableSet<V>> builder = ImmutableMap.builder(); int size = 0; for (Entry<? extends K, ? extends Collection<? extends V>> entry : multimap.asMap().entrySet()) { K key = entry.getKey(); Collection<? extends V> values = entry.getValue(); ImmutableSet<V> set = valueSet(valueComparator, values); if (!set.isEmpty()) { builder.put(key, set); size += set.size(); } } return new ImmutableSetMultimap<K, V>( builder.build(), size, valueComparator); } /** * Returned by get() when a missing key is provided. Also holds the * comparator, if any, used for values. */ private final transient ImmutableSet<V> emptySet; ImmutableSetMultimap(ImmutableMap<K, ImmutableSet<V>> map, int size, @Nullable Comparator<? super V> valueComparator) { super(map, size); this.emptySet = emptySet(valueComparator); } // views /** * Returns an immutable set of the values for the given key. If no mappings * in the multimap have the provided key, an empty immutable set is returned. * The values are in the same order as the parameters used to build this * multimap. */ @Override public ImmutableSet<V> get(@Nullable K key) { // This cast is safe as its type is known in constructor. ImmutableSet<V> set = (ImmutableSet<V>) map.get(key); return firstNonNull(set, emptySet); } private transient ImmutableSetMultimap<V, K> inverse; /** * {@inheritDoc} * * <p>Because an inverse of a set multimap cannot contain multiple pairs with * the same key and value, this method returns an {@code ImmutableSetMultimap} * rather than the {@code ImmutableMultimap} specified in the {@code * ImmutableMultimap} class. * * @since 11.0 */ public ImmutableSetMultimap<V, K> inverse() { ImmutableSetMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; } private ImmutableSetMultimap<V, K> invert() { Builder<V, K> builder = builder(); for (Entry<K, V> entry : entries()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableSetMultimap<V, K> invertedMultimap = builder.build(); invertedMultimap.inverse = this; return invertedMultimap; } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableSet<V> removeAll(Object key) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the multimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public ImmutableSet<V> replaceValues( K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private transient ImmutableSet<Entry<K, V>> entries; /** * Returns an immutable collection of all key-value pairs in the multimap. * Its iterator traverses the values for the first key, the values for the * second key, and so on. */ @Override public ImmutableSet<Entry<K, V>> entries() { ImmutableSet<Entry<K, V>> result = entries; return (result == null) ? (entries = new EntrySet<K, V>(this)) : result; } private static final class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> { private transient final ImmutableSetMultimap<K, V> multimap; EntrySet(ImmutableSetMultimap<K, V> multimap) { this.multimap = multimap; } @Override public boolean contains(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) object; return multimap.containsEntry(entry.getKey(), entry.getValue()); } return false; } @Override public int size() { return multimap.size(); } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return multimap.entryIterator(); } @Override boolean isPartialView() { return false; } } private static <V> ImmutableSet<V> valueSet( @Nullable Comparator<? super V> valueComparator, Collection<? extends V> values) { return (valueComparator == null) ? ImmutableSet.copyOf(values) : ImmutableSortedSet.copyOf(valueComparator, values); } private static <V> ImmutableSet<V> emptySet( @Nullable Comparator<? super V> valueComparator) { return (valueComparator == null) ? ImmutableSet.<V>of() : ImmutableSortedSet.<V>emptySet(valueComparator); } /** * @serialData number of distinct keys, and then for each distinct key: the * key, the number of values for that key, and the key's values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(valueComparator()); Serialization.writeMultimap(this, stream); } @Nullable Comparator<? super V> valueComparator() { return emptySet instanceof ImmutableSortedSet ? ((ImmutableSortedSet<V>) emptySet).comparator() : null; } @GwtIncompatible("java.io.ObjectInputStream") // Serialization type safety is at the caller's mercy. @SuppressWarnings("unchecked") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); Comparator<Object> valueComparator = (Comparator<Object>) stream.readObject(); int keyCount = stream.readInt(); if (keyCount < 0) { throw new InvalidObjectException("Invalid key count " + keyCount); } ImmutableMap.Builder<Object, ImmutableSet<Object>> builder = ImmutableMap.builder(); int tmpSize = 0; for (int i = 0; i < keyCount; i++) { Object key = stream.readObject(); int valueCount = stream.readInt(); if (valueCount <= 0) { throw new InvalidObjectException("Invalid value count " + valueCount); } Object[] array = new Object[valueCount]; for (int j = 0; j < valueCount; j++) { array[j] = stream.readObject(); } ImmutableSet<Object> valueSet = valueSet(valueComparator, asList(array)); if (valueSet.size() != array.length) { throw new InvalidObjectException( "Duplicate key-value pairs exist for key " + key); } builder.put(key, valueSet); tmpSize += valueCount; } ImmutableMap<Object, ImmutableSet<Object>> tmpMap; try { tmpMap = builder.build(); } catch (IllegalArgumentException e) { throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e); } FieldSettersHolder.MAP_FIELD_SETTER.set(this, tmpMap); FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); FieldSettersHolder.EMPTY_SET_FIELD_SETTER.set( this, emptySet(valueComparator)); } @GwtIncompatible("not needed in emulated source.") private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * A {@code RegularImmutableTable} optimized for dense data. */ @GwtCompatible @Immutable final class DenseImmutableTable<R, C, V> extends RegularImmutableTable<R, C, V> { private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final ImmutableMap<R, Map<C, V>> rowMap; private final ImmutableMap<C, Map<R, V>> columnMap; private final int[] rowCounts; private final int[] columnCounts; private final V[][] values; private final int[] iterationOrderRow; private final int[] iterationOrderColumn; private static <E> ImmutableMap<E, Integer> makeIndex(ImmutableSet<E> set) { ImmutableMap.Builder<E, Integer> indexBuilder = ImmutableMap.builder(); int i = 0; for (E key : set) { indexBuilder.put(key, i); i++; } return indexBuilder.build(); } DenseImmutableTable(ImmutableList<Cell<R, C, V>> cellList, ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) { @SuppressWarnings("unchecked") V[][] array = (V[][]) new Object[rowSpace.size()][columnSpace.size()]; this.values = array; this.rowKeyToIndex = makeIndex(rowSpace); this.columnKeyToIndex = makeIndex(columnSpace); rowCounts = new int[rowKeyToIndex.size()]; columnCounts = new int[columnKeyToIndex.size()]; int[] iterationOrderRow = new int[cellList.size()]; int[] iterationOrderColumn = new int[cellList.size()]; for (int i = 0; i < cellList.size(); i++) { Cell<R, C, V> cell = cellList.get(i); R rowKey = cell.getRowKey(); C columnKey = cell.getColumnKey(); int rowIndex = rowKeyToIndex.get(rowKey); int columnIndex = columnKeyToIndex.get(columnKey); V existingValue = values[rowIndex][columnIndex]; checkArgument(existingValue == null, "duplicate key: (%s, %s)", rowKey, columnKey); values[rowIndex][columnIndex] = cell.getValue(); rowCounts[rowIndex]++; columnCounts[columnIndex]++; iterationOrderRow[i] = rowIndex; iterationOrderColumn[i] = columnIndex; } this.iterationOrderRow = iterationOrderRow; this.iterationOrderColumn = iterationOrderColumn; this.rowMap = new RowMap(); this.columnMap = new ColumnMap(); } /** * An immutable map implementation backed by an indexed nullable array. */ private abstract static class ImmutableArrayMap<K, V> extends ImmutableMap<K, V> { private final int size; ImmutableArrayMap(int size) { this.size = size; } abstract ImmutableMap<K, Integer> keyToIndex(); // True if getValue never returns null. private boolean isFull() { return size == keyToIndex().size(); } K getKey(int index) { return keyToIndex().keySet().asList().get(index); } @Nullable abstract V getValue(int keyIndex); @Override ImmutableSet<K> createKeySet() { return isFull() ? keyToIndex().keySet() : super.createKeySet(); } @Override public int size() { return size; } @Override public V get(@Nullable Object key) { Integer keyIndex = keyToIndex().get(key); return (keyIndex == null) ? null : getValue(keyIndex); } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new ImmutableMapEntrySet<K, V>() { @Override ImmutableMap<K, V> map() { return ImmutableArrayMap.this; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return new AbstractIterator<Entry<K, V>>() { private int index = -1; private final int maxIndex = keyToIndex().size(); @Override protected Entry<K, V> computeNext() { for (index++; index < maxIndex; index++) { V value = getValue(index); if (value != null) { return Maps.immutableEntry(getKey(index), value); } } return endOfData(); } }; } }; } } private final class Row extends ImmutableArrayMap<C, V> { private final int rowIndex; Row(int rowIndex) { super(rowCounts[rowIndex]); this.rowIndex = rowIndex; } @Override ImmutableMap<C, Integer> keyToIndex() { return columnKeyToIndex; } @Override V getValue(int keyIndex) { return values[rowIndex][keyIndex]; } @Override boolean isPartialView() { return true; } } private final class Column extends ImmutableArrayMap<R, V> { private final int columnIndex; Column(int columnIndex) { super(columnCounts[columnIndex]); this.columnIndex = columnIndex; } @Override ImmutableMap<R, Integer> keyToIndex() { return rowKeyToIndex; } @Override V getValue(int keyIndex) { return values[keyIndex][columnIndex]; } @Override boolean isPartialView() { return true; } } private final class RowMap extends ImmutableArrayMap<R, Map<C, V>> { private RowMap() { super(rowCounts.length); } @Override ImmutableMap<R, Integer> keyToIndex() { return rowKeyToIndex; } @Override Map<C, V> getValue(int keyIndex) { return new Row(keyIndex); } @Override boolean isPartialView() { return false; } } private final class ColumnMap extends ImmutableArrayMap<C, Map<R, V>> { private ColumnMap() { super(columnCounts.length); } @Override ImmutableMap<C, Integer> keyToIndex() { return columnKeyToIndex; } @Override Map<R, V> getValue(int keyIndex) { return new Column(keyIndex); } @Override boolean isPartialView() { return false; } } @Override public ImmutableMap<C, Map<R, V>> columnMap() { return columnMap; } @Override public ImmutableMap<R, Map<C, V>> rowMap() { return rowMap; } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return ((rowIndex == null) || (columnIndex == null)) ? null : values[rowIndex][columnIndex]; } @Override public int size() { return iterationOrderRow.length; } @Override Cell<R, C, V> getCell(int index) { int rowIndex = iterationOrderRow[index]; int columnIndex = iterationOrderColumn[index]; R rowKey = rowKeySet().asList().get(rowIndex); C columnKey = columnKeySet().asList().get(columnIndex); V value = values[rowIndex][columnIndex]; return cellOf(rowKey, columnKey, value); } @Override V getValue(int index) { return values[iterationOrderRow[index]][iterationOrderColumn[index]]; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * An iterator which forwards all its method calls to another iterator. * Subclasses should override one or more methods to modify the behavior of the * backing iterator as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingIterator<T> extends ForwardingObject implements Iterator<T> { /** Constructor for use by subclasses. */ protected ForwardingIterator() {} @Override protected abstract Iterator<T> delegate(); @Override public boolean hasNext() { return delegate().hasNext(); } @Override public T next() { return delegate().next(); } @Override public void remove() { delegate().remove(); } }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@code Iterable}. Except as noted, each method has a corresponding * {@link Iterator}-based method in the {@link Iterators} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables * produced in this class are <i>lazy</i>, which means that their iterators * only advance the backing iteration when absolutely necessary. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterables}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterables { private Iterables() {} /** Returns an unmodifiable view of {@code iterable}. */ public static <T> Iterable<T> unmodifiableIterable( final Iterable<T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { return iterable; } return new UnmodifiableIterable<T>(iterable); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Iterable<E> unmodifiableIterable( ImmutableCollection<E> iterable) { return checkNotNull(iterable); } private static final class UnmodifiableIterable<T> extends FluentIterable<T> { private final Iterable<T> iterable; private UnmodifiableIterable(Iterable<T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** * Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)} * is true. */ public static boolean contains(Iterable<?> iterable, @Nullable Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; return Collections2.safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided * collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a * collection, and {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ public static boolean removeAll( Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the * provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a * collection, and {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ public static boolean retainAll( Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided * predicate. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterable * * @throws UnsupportedOperationException if the iterable does not support * {@code remove()}. * @since 2.0 */ public static <T> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { return removeIfFromRandomAccessList( (List<T>) removeFrom, checkNotNull(predicate)); } return Iterators.removeIf(removeFrom.iterator(), predicate); } private static <T> boolean removeIfFromRandomAccessList( List<T> list, Predicate<? super T> predicate) { // Note: Not all random access lists support set() so we need to deal with // those that don't and attempt the slower remove() based solution. int from = 0; int to = 0; for (; from < list.size(); from++) { T element = list.get(from); if (!predicate.apply(element)) { if (from > to) { try { list.set(to, element); } catch (UnsupportedOperationException e) { slowRemoveIfForRemainingElements(list, predicate, to, from); return true; } } to++; } } // Clear the tail of any remaining items list.subList(to, list.size()).clear(); return from != to; } private static <T> void slowRemoveIfForRemainingElements(List<T> list, Predicate<? super T> predicate, int to, int from) { // Here we know that: // * (to < from) and that both are valid indices. // * Everything with (index < to) should be kept. // * Everything with (to <= index < from) should be removed. // * The element with (index == from) should be kept. // * Everything with (index > from) has not been checked yet. // Check from the end of the list backwards (minimize expected cost of // moving elements when remove() is called). Stop before 'from' because // we already know that should be kept. for (int n = list.size() - 1; n > from; n--) { if (predicate.apply(list.get(n))) { list.remove(n); } } // And now remove everything in the range [to, from) (going backwards). for (int n = from - 1; n >= to; n--) { list.remove(n); } } /** * Removes and returns the first matching element, or returns {@code null} if there is none. */ @Nullable static <T> T removeFirstMatching(Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; } /** * Determines whether two iterables contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterable1} * and {@code iterable2} contain the same number of elements and every element * of {@code iterable1} is equal to the corresponding element of * {@code iterable2}. */ public static boolean elementsEqual( Iterable<?> iterable1, Iterable<?> iterable2) { if (iterable1 instanceof Collection && iterable2 instanceof Collection) { Collection<?> collection1 = (Collection<?>) iterable1; Collection<?> collection2 = (Collection<?>) iterable2; if (collection1.size() != collection2.size()) { return false; } } return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format * {@code [e1, e2, ..., en]}. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple * elements */ public static <T> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code * defaultValue} if the iterable is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements */ @Nullable public static <T> T getOnlyElement( Iterable<? extends T> iterable, @Nullable T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterable * have been copied */ @GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { Collection<? extends T> collection = toCollection(iterable); T[] array = ObjectArrays.newArray(type, collection.size()); return collection.toArray(array); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable * have been copied */ static Object[] toArray(Iterable<?> iterable) { return toCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is * created with the contents of the iterable in the same iteration order. */ private static <E> Collection<E> toCollection(Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this * operation. */ public static <T> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = Collections2.cast(elementsToAdd); return addTo.addAll(c); } return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); } /** * Returns the number of elements in the specified iterable that equal the * specified object. This implementation avoids a full iteration when the * iterable is a {@link Multiset} or {@link Set}. * * @see Collections#frequency */ public static int frequency(Iterable<?> iterable, @Nullable Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } else if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of * {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} * does. After {@code remove()} is called, subsequent cycles omit the removed * element, which is no longer in {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code iterable} is * empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. * * <p>To cycle over the iterable {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, iterable))} */ public static <T> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided * elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed * element will no longer appear in either that iterator or any other iterator * created from the same source iterable. That is, this method behaves exactly * as {@code Iterables.cycle(Lists.newArrayList(elements))}. The iterator's * {@code hasNext} method returns {@code true} until all of the original * elements have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. * * <p>To cycle over the elements {@code n} times, use the following: * {@code Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} */ public static <T> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an * iterator that traverses the elements in {@code a}, followed by the elements * in {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { return concat(ImmutableList.of(a, b)); } /** * Combines three iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { return concat(ImmutableList.of(a, b, c)); } /** * Combines four iterables into a single iterable. The returned iterable has * an iterator that traverses the elements in {@code a}, followed by the * elements in {@code b}, followed by the elements in {@code c}, followed by * the elements in {@code d}. The source iterators are not polled until * necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. */ public static <T> Iterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { return concat(ImmutableList.of(a, b, c, d)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. * * @throws NullPointerException if any of the provided iterables is null */ public static <T> Iterable<T> concat(Iterable<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs)); } /** * Combines multiple iterables into a single iterable. The returned iterable * has an iterator that traverses the elements of each iterable in * {@code inputs}. The input iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the * corresponding input iterator supports it. The methods of the returned * iterable may throw {@code NullPointerException} if any of the input * iterators is null. */ public static <T> Iterable<T> concat( final Iterable<? extends Iterable<? extends T>> inputs) { checkNotNull(inputs); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.concat(iterators(inputs)); } }; } /** * Returns an iterator over the iterators of the given iterables. */ private static <T> Iterator<Iterator<? extends T>> iterators( Iterable<? extends Iterable<? extends T>> iterables) { return new TransformedIterator<Iterable<? extends T>, Iterator<? extends T>>( iterables.iterator()) { @Override Iterator<? extends T> transform(Iterable<? extends T> from) { return from.iterator(); } }; } /** * Divides an iterable into unmodifiable sublists of the given size (the final * iterable may be smaller). For example, partitioning an iterable containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of * three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. The returned lists implement {@link * RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link * Lists#partition(List, int)} instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> partition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding * the final iterable with null values if necessary. For example, partitioning * an iterable containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing * two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link * Iterator#remove()} method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code * iterable} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> Iterable<List<T>> paddedPartition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * resulting iterable's iterator does not support {@code remove()}. */ public static <T> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } }; } /** * Returns all instances of class {@code type} in {@code unfiltered}. The * returned iterable has elements whose class is {@code type} or a subclass of * {@code type}. The returned iterable's iterator does not support * {@code remove()}. * * @param unfiltered an iterable containing objects of any type * @param type the type of elements desired * @return an unmodifiable iterable containing all elements of the original * iterable that were of the requested type */ @GwtIncompatible("Class.isInstance") public static <T> Iterable<T> filter( final Iterable<?> unfiltered, final Class<T> type) { checkNotNull(unfiltered); checkNotNull(type); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), type); } }; } /** * Returns {@code true} if any element in {@code iterable} satisfies the predicate. */ public static <T> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the * predicate. If {@code iterable} is empty, {@code true} is returned. */ public static <T> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate; use this method only when such an element is known to exist. If * it is possible that <i>no</i> element will match, use {@link #tryFind} or * {@link #find(Iterable, Predicate, Object)} instead. * * @throws NoSuchElementException if no element in {@code iterable} matches * the given predicate */ public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given * predicate, or {@code defaultValue} if none found. Note that this can * usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * @since 7.0 */ @Nullable public static <T> T find(Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) { return Iterators.find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * iterable} that satisfies the given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterable}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterable has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true}, * or {@code -1} if there is no such index. * * @since 2.0 */ public static <T> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns an iterable that applies {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if the * provided iterator does. After a successful {@code remove()} call, * {@code fromIterable} no longer contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other * {@code Collection}, consider {@link Lists#transform} and {@link * Collections2#transform}. */ public static <F, T> Iterable<T> transform(final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } }; } /** * Returns the element at the specified position in an iterable. * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the size of {@code iterable} */ public static <T> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); } /** * Returns the element at the specified position in an iterable or a default * value otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is * greater than or equal to the size of the iterable * @return the element at the specified position in {@code iterable} or * {@code defaultValue} if {@code iterable} contains fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterable<? extends T> iterable, int position, @Nullable T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = Lists.cast(iterable); return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if * the iterable is empty. The {@link Iterators} analog to this method is * {@link Iterators#getNext}. * * <p>If no default value is desired (and the caller instead wants a * {@link NoSuchElementException} to be thrown), it is recommended that * {@code iterable.iterator().next()} is used instead. * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ @Nullable public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ public static <T> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if * the iterable is empty. * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ @Nullable public static <T> T getLast(Iterable<? extends T> iterable, @Nullable T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = Collections2.cast(iterable); if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList(Lists.cast(iterable)); } } return Iterators.getLast(iterable.iterator(), defaultValue); } private static <T> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first * {@code numberToSkip} elements. If {@code iterable} contains fewer than * {@code numberToSkip} elements, the returned iterable skips all of its * elements. * * <p>Modifications to the underlying {@link Iterable} before a call to * {@code iterator()} are reflected in the returned iterator. That is, the * iterator skips the first {@code numberToSkip} elements that exist when the * {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the * iterator of the underlying iterable supports it. Note that it is * <i>not</i> possible to delete the last skipped element by immediately * calling {@code remove()} on that iterator, as the {@code Iterator} * contract states that a call to {@code remove()} before a call to * {@code next()} will throw an {@link IllegalStateException}. * * @since 3.0 */ public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); if (iterable instanceof List) { final List<T> list = (List<T>) iterable; return new FluentIterable<T>() { @Override public Iterator<T> iterator() { // TODO(kevinb): Support a concurrently modified collection? int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } }; } return new FluentIterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { Iterators.checkRemove(!atStart); iterator.remove(); } }; } }; } /** * Creates an iterable with the first {@code limitSize} elements of the given * iterable. If the original iterable does not contain that many elements, the * returned iterator will have the same behavior as the original iterable. The * returned iterable's iterator supports {@code remove()} if the original * iterator does. * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterable<T> limit( final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } }; } /** * Returns a view of the supplied iterable that wraps each generated * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will * get entries from {@link Queue#remove()} since {@link Queue}'s iteration * order is undefined. Calling {@link Iterator#hasNext()} on a generated * iterator from the returned iterable may cause an item to be immediately * dequeued for return on a subsequent call to {@link Iterator#next()}. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator * through {@link Iterators#consumingIterator(Iterator)}; for queues, * an iterable that generates iterators that return and consume the * queue's elements in queue order * * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) { if (iterable instanceof Queue) { return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return new ConsumingQueueIterator<T>((Queue<T>) iterable); } }; } checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.consumingIterator(iterable.iterator()); } }; } private static class ConsumingQueueIterator<T> extends AbstractIterator<T> { private final Queue<T> queue; private ConsumingQueueIterator(Queue<T> queue) { this.queue = queue; } @Override public T computeNext() { try { return queue.remove(); } catch (NoSuchElementException e) { return endOfData(); } } } // Methods only in Iterables, not in Iterators /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since * one can only ask an iterator whether it has any elements <i>remaining</i> * (which one does using {@link Iterator#hasNext}). * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** * Returns an iterable over the merged contents of all given * {@code iterables}. Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterables.<T>toIterator()), comparator); } }; return new UnmodifiableIterable<T>(iterable); } // TODO(user): Is this the best place for this? Move to fluent functions? // Useful as a public method? private static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() { return new Function<Iterable<? extends T>, Iterator<? extends T>>() { @Override public Iterator<? extends T> apply(Iterable<? extends T> iterable) { return iterable.iterator(); } }; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2.FilteredCollection; import java.io.Serializable; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Set} instances. Also see this * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Sets"> * {@code Sets}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @author Chris Povirk * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Sets { private Sets() {} /** * {@link AbstractSet} substitute without the potentially-quadratic * {@code removeAll} implementation. */ abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> { @Override public boolean removeAll(Collection<?> c) { return removeAllImpl(this, c); } @Override public boolean retainAll(Collection<?> c) { return super.retainAll(checkNotNull(c)); // GWT compatibility } } /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements are provided to the method. * * @param anElement one of the elements the set should contain * @param otherElements the rest of the elements the set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( E anElement, E... otherElements) { return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); } /** * Returns an immutable set instance containing the given enum elements. * Internally, the returned set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration * order, not the order in which the elements appear in the given collection. * * @param elements the elements, all of the same {@code enum} type, that the * set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( Iterable<E> elements) { if (elements instanceof ImmutableEnumSet) { return (ImmutableEnumSet<E>) elements; } else if (elements instanceof Collection) { Collection<E> collection = (Collection<E>) elements; if (collection.isEmpty()) { return ImmutableSet.of(); } else { return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection)); } } else { Iterator<E> itr = elements.iterator(); if (itr.hasNext()) { EnumSet<E> enumSet = EnumSet.of(itr.next()); Iterators.addAll(enumSet, itr); return ImmutableEnumSet.asImmutable(enumSet); } else { return ImmutableSet.of(); } } } /** * Returns a new {@code EnumSet} instance containing the given elements. * Unlike {@link EnumSet#copyOf(Collection)}, this method does not produce an * exception on an empty collection, and it may be called on any iterable, not * just a {@code Collection}. */ public static <E extends Enum<E>> EnumSet<E> newEnumSet(Iterable<E> iterable, Class<E> elementType) { EnumSet<E> set = EnumSet.noneOf(elementType); Iterables.addAll(set, iterable); return set; } // HashSet /** * Creates a <i>mutable</i>, empty {@code HashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * @return a new, empty {@code HashSet} */ public static <E> HashSet<E> newHashSet() { return new HashSet<E>(); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use an overload of {@link ImmutableSet#of()} (for varargs) or * {@link ImmutableSet#copyOf(Object[])} (for an array) instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#of(Enum, Enum[])} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { HashSet<E> set = newHashSetWithExpectedSize(elements.length); Collections.addAll(set, elements); return set; } /** * Creates a {@code HashSet} instance, with a high enough "initial capacity" * that it <i>should</i> hold {@code 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 <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code HashSet} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) { return new HashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use * {@link #newEnumSet(Iterable, Class)} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) { return (elements instanceof Collection) ? new HashSet<E>(Collections2.cast(elements)) : newHashSet(elements.iterator()); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given * elements in unspecified order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an * {@link EnumSet} instead. * * @param elements the elements that the set should contain * @return a new {@code HashSet} containing those elements (minus duplicates) */ public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) { HashSet<E> set = newHashSet(); Iterators.addAll(set, elements); return set; } /** * Creates a thread-safe set backed by a hash map. The set is backed by a * {@link ConcurrentHashMap} instance, and thus carries the same concurrency * guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be * used as an element. The set is serializable. * * @return a new, empty thread-safe {@code Set} * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet() { return newSetFromMap(new ConcurrentHashMap<E, Boolean>()); } /** * Creates a thread-safe set backed by a hash map and containing the given * elements. The set is backed by a {@link ConcurrentHashMap} instance, and * thus carries the same concurrency guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be * used as an element. The set is serializable. * * @param elements the elements that the set should contain * @return a new thread-safe set containing those elements (minus duplicates) * @throws NullPointerException if {@code elements} or any of its contents is * null * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet( Iterable<? extends E> elements) { Set<E> set = newConcurrentHashSet(); Iterables.addAll(set, elements); return set; } // LinkedHashSet /** * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSet#of()} instead. * * @return a new, empty {@code LinkedHashSet} */ public static <E> LinkedHashSet<E> newLinkedHashSet() { return new LinkedHashSet<E>(); } /** * Creates a {@code LinkedHashSet} instance, with a high enough "initial * capacity" that it <i>should</i> hold {@code 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 <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the * returned set * @return a new, empty {@code LinkedHashSet} with enough capacity to hold * {@code expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 11.0 */ public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize( int expectedSize) { return new LinkedHashSet<E>(Maps.capacity(expectedSize)); } /** * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the * given elements in order. * * <p><b>Note:</b> if mutability is not required and the elements are * non-null, use {@link ImmutableSet#copyOf(Iterable)} instead. * * @param elements the elements that the set should contain, in order * @return a new {@code LinkedHashSet} containing those elements (minus * duplicates) */ public static <E> LinkedHashSet<E> newLinkedHashSet( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedHashSet<E>(Collections2.cast(elements)); } LinkedHashSet<E> set = newLinkedHashSet(); Iterables.addAll(set, elements); return set; } // TreeSet /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the * natural sort ordering of its elements. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#of()} instead. * * @return a new, empty {@code TreeSet} */ public static <E extends Comparable> TreeSet<E> newTreeSet() { return new TreeSet<E>(); } /** * Creates a <i>mutable</i> {@code TreeSet} instance containing the given * elements sorted by their natural ordering. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit * comparator, this method has different behavior than * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with * that comparator. * * @param elements the elements that the set should contain * @return a new {@code TreeSet} containing those elements (minus duplicates) */ public static <E extends Comparable> TreeSet<E> newTreeSet( Iterable<? extends E> elements) { TreeSet<E> set = newTreeSet(); Iterables.addAll(set, elements); return set; } /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given * comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedSet.orderedBy(comparator).build()} instead. * * @param comparator the comparator to use to sort the set * @return a new, empty {@code TreeSet} * @throws NullPointerException if {@code comparator} is null */ public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) { return new TreeSet<E>(checkNotNull(comparator)); } /** * Creates an empty {@code Set} that uses identity to determine equality. It * compares object references, instead of calling {@code equals}, to * determine whether a provided object matches an element in the set. For * example, {@code contains} returns {@code false} when passed an object that * equals a set member, but isn't the same instance. This behavior is similar * to the way {@code IdentityHashMap} handles key lookups. * * @since 8.0 */ public static <E> Set<E> newIdentityHashSet() { return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap()); } /** * Creates an empty {@code CopyOnWriteArraySet} instance. * * <p><b>Note:</b> if you need an immutable empty {@link Set}, use * {@link Collections#emptySet} instead. * * @return a new, empty {@code CopyOnWriteArraySet} * @since 12.0 */ @GwtIncompatible("CopyOnWriteArraySet") public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() { return new CopyOnWriteArraySet<E>(); } /** * Creates a {@code CopyOnWriteArraySet} instance containing the given elements. * * @param elements the elements that the set should contain, in order * @return a new {@code CopyOnWriteArraySet} containing those elements * @since 12.0 */ @GwtIncompatible("CopyOnWriteArraySet") public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet( Iterable<? extends E> elements) { // We copy elements to an ArrayList first, rather than incurring the // quadratic cost of adding them to the COWAS directly. Collection<? extends E> elementsCollection = (elements instanceof Collection) ? Collections2.cast(elements) : Lists.newArrayList(elements); return new CopyOnWriteArraySet<E>(elementsCollection); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. If the collection is an {@link EnumSet}, this * method has the same behavior as {@link EnumSet#complementOf}. Otherwise, * the specified collection must contain at least one element, in order to * determine the element type. If the collection could be empty, use * {@link #complementOf(Collection, Class)} instead of this method. * * @param collection the collection whose complement should be stored in the * enum set * @return a new, modifiable {@code EnumSet} containing all values of the enum * that aren't present in the given collection * @throws IllegalArgumentException if {@code collection} is not an * {@code EnumSet} instance and contains no elements */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection) { if (collection instanceof EnumSet) { return EnumSet.complementOf((EnumSet<E>) collection); } checkArgument(!collection.isEmpty(), "collection is empty; use the other version of this method"); Class<E> type = collection.iterator().next().getDeclaringClass(); return makeComplementByHand(collection, type); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in * the specified collection. This is equivalent to * {@link EnumSet#complementOf}, but can act on any input collection, as long * as the elements are of enum type. * * @param collection the collection whose complement should be stored in the * {@code EnumSet} * @param type the type of the elements in the set * @return a new, modifiable {@code EnumSet} initially containing all the * values of the enum not present in the given collection */ public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection, Class<E> type) { checkNotNull(collection); return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet<E>) collection) : makeComplementByHand(collection, type); } private static <E extends Enum<E>> EnumSet<E> makeComplementByHand( Collection<E> collection, Class<E> type) { EnumSet<E> result = EnumSet.allOf(type); result.removeAll(collection); return result; } /** * Returns a set backed by the specified map. The resulting set displays * the same ordering, concurrency, and performance characteristics as the * backing map. In essence, this factory method provides a {@link Set} * implementation corresponding to any {@link Map} implementation. There is no * need to use this method on a {@link Map} implementation that already has a * corresponding {@link Set} implementation (such as {@link java.util.HashMap} * or {@link java.util.TreeMap}). * * <p>Each method invocation on the set returned by this method results in * exactly one method invocation on the backing map or its {@code keySet} * view, with one exception. The {@code addAll} method is implemented as a * sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, * and should not be accessed directly after this method returns. These * conditions are ensured if the map is created empty, passed directly * to this method, and no reference to the map is retained, as illustrated * in the following code fragment: <pre> {@code * * Set<Object> identityHashSet = Sets.newSetFromMap( * new IdentityHashMap<Object, Boolean>());}</pre> * * <p>This method has the same behavior as the JDK 6 method * {@code Collections.newSetFromMap()}. The returned set is serializable if * the backing map is. * * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty */ public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return Platform.newSetFromMap(map); } /** * An unmodifiable view of a set which may be backed by other sets; this view * will change as the backing sets do. Contains methods to copy the data into * a new set which will then remain stable. There is usually no reason to * retain a reference of type {@code SetView}; typically, you either use it * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or * {@link #copyInto} and forget the {@code SetView} itself. * * @since 2.0 (imported from Google Collections Library) */ public abstract static class SetView<E> extends AbstractSet<E> { private SetView() {} // no subclasses but our own /** * Returns an immutable copy of the current contents of this set view. * Does not support null elements. * * <p><b>Warning:</b> this may have unexpected results if a backing set of * this view uses a nonstandard notion of equivalence, for example if it is * a {@link TreeSet} using a comparator that is inconsistent with {@link * Object#equals(Object)}. */ public ImmutableSet<E> immutableCopy() { return ImmutableSet.copyOf(this); } /** * Copies the current contents of this set view into an existing set. This * method has equivalent behavior to {@code set.addAll(this)}, assuming that * all the sets involved are based on the same notion of equivalence. * * @return a reference to {@code set}, for convenience */ // Note: S should logically extend Set<? super E> but can't due to either // some javac bug or some weirdness in the spec, not sure which. public <S extends Set<E>> S copyInto(S set) { set.addAll(this); return set; } } /** * Returns an unmodifiable <b>view</b> of the union of two sets. The returned * set contains all elements that are contained in either backing set. * Iterating over the returned set iterates first over all the elements of * {@code set1}, then over each element of {@code set2}, in order, that is not * contained in {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and * the {@link Map#keySet} of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs better when {@code set1} is the * smaller of the two sets. If you have reason to believe one of your sets * will generally be smaller than the other, pass it first. * * <p>Further, note that the current implementation is not suitable for nested * {@code union} views, i.e. the following should be avoided when in a loop: * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting * set has a cubic complexity to the depth of the nesting. */ public static <E> SetView<E> union( final Set<? extends E> set1, final Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Set<? extends E> set2minus1 = difference(set2, set1); return new SetView<E>() { @Override public int size() { return set1.size() + set2minus1.size(); } @Override public boolean isEmpty() { return set1.isEmpty() && set2.isEmpty(); } @Override public Iterator<E> iterator() { return Iterators.unmodifiableIterator( Iterators.concat(set1.iterator(), set2minus1.iterator())); } @Override public boolean contains(Object object) { return set1.contains(object) || set2.contains(object); } @Override public <S extends Set<E>> S copyInto(S set) { set.addAll(set1); set.addAll(set2); return set; } @Override public ImmutableSet<E> immutableCopy() { return new ImmutableSet.Builder<E>() .addAll(set1).addAll(set2).build(); } }; } /** * Returns an unmodifiable <b>view</b> of the intersection of two sets. The * returned set contains all elements that are contained by both backing sets. * The iteration order of the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * <p><b>Note:</b> The returned view performs slightly better when {@code * set1} is the smaller of the two sets. If you have reason to believe one of * your sets will generally be smaller than the other, pass it first. * Unfortunately, since this method sets the generic type of the returned set * based on the type of the first set passed, this could in rare cases force * you to make a cast, for example: <pre> {@code * * Set<Object> aFewBadObjects = ... * Set<String> manyBadStrings = ... * * // impossible for a non-String to be in the intersection * SuppressWarnings("unchecked") * Set<String> badStrings = (Set) Sets.intersection( * aFewBadObjects, manyBadStrings);}</pre> * * <p>This is unfortunate, but should come up only very rarely. */ public static <E> SetView<E> intersection( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> inSet2 = Predicates.in(set2); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), inSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return !iterator().hasNext(); } @Override public boolean contains(Object object) { return set1.contains(object) && set2.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return set1.containsAll(collection) && set2.containsAll(collection); } }; } /** * Returns an unmodifiable <b>view</b> of the difference of two sets. The * returned set contains all elements that are contained by {@code set1} and * not contained by {@code set2}. {@code set2} may also contain elements not * present in {@code set1}; these are simply ignored. The iteration order of * the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). */ public static <E> SetView<E> difference( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2)); return new SetView<E>() { @Override public Iterator<E> iterator() { return Iterators.filter(set1.iterator(), notInSet2); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean isEmpty() { return set2.containsAll(set1); } @Override public boolean contains(Object element) { return set1.contains(element) && !set2.contains(element); } }; } /** * Returns an unmodifiable <b>view</b> of the symmetric difference of two * sets. The returned set contains all elements that are contained in either * {@code set1} or {@code set2} but not in both. The iteration order of the * returned set is undefined. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based * on different equivalence relations (as {@code HashSet}, {@code TreeSet}, * and the keySet of an {@code IdentityHashMap} all are). * * @since 3.0 */ public static <E> SetView<E> symmetricDifference( Set<? extends E> set1, Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); // TODO(kevinb): Replace this with a more efficient implementation return difference(union(set1, set2), intersection(set1, set2)); } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned set is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as {@code * removeAll()} and {@code clear()} are called on the filtered set, only * elements that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate * across every element in the underlying set and determine which elements * satisfy the filter. When a live view is <i>not</i> needed, it may be faster * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent * with equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) */ // TODO(kevinb): how to omit that last sentence when building GWT javadoc? public static <E> Set<E> filter( Set<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof SortedSet) { return filter((SortedSet<E>) unfiltered, predicate); } if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSet<E>( (Set<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> { FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public boolean equals(@Nullable Object object) { return equalsImpl(this, object); } @Override public int hashCode() { return hashCodeImpl(this); } } /** * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that * satisfy a predicate. The returned set is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as * {@code removeAll()} and {@code clear()} are called on the filtered set, * only elements that satisfy the filter will be removed from the underlying * set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across * every element in the underlying set and determine which elements satisfy * the filter. When a live view is <i>not</i> needed, it may be faster to copy * {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such as * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with * equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) * * @since 11.0 */ public static <E> SortedSet<E> filter( SortedSet<E> unfiltered, Predicate<? super E> predicate) { return Platform.setsFilterSortedSet(unfiltered, predicate); } static <E> SortedSet<E> filterSortedIgnoreNavigable( SortedSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredSortedSet<E>( (SortedSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSortedSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSortedSet<E> extends FilteredSet<E> implements SortedSet<E> { FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public Comparator<? super E> comparator() { return ((SortedSet<E>) unfiltered).comparator(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); } @Override public SortedSet<E> headSet(E toElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); } @Override public SortedSet<E> tailSet(E fromElement) { return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); } @Override public E first() { return iterator().next(); } @Override public E last() { SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; while (true) { E element = sortedUnfiltered.last(); if (predicate.apply(element)) { return element; } sortedUnfiltered = sortedUnfiltered.headSet(element); } } } /** * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that * satisfy a predicate. The returned set is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all * other set methods are supported. When given an element that doesn't satisfy * the predicate, the set's {@code add()} and {@code addAll()} methods throw * an {@link IllegalArgumentException}. When methods such as * {@code removeAll()} and {@code clear()} are called on the filtered set, * only elements that satisfy the filter will be removed from the underlying * set. * * <p>The returned set isn't threadsafe or serializable, even if * {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across * every element in the underlying set and determine which elements satisfy * the filter. When a live view is <i>not</i> needed, it may be faster to copy * {@code Iterables.filter(unfiltered, predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, * as documented at {@link Predicate#apply}. Do not provide a predicate such as * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with * equals. (See {@link Iterables#filter(Iterable, Class)} for related * functionality.) * * @since 14.0 */ @GwtIncompatible("NavigableSet") @SuppressWarnings("unchecked") public static <E> NavigableSet<E> filter( NavigableSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredNavigableSet<E>( (NavigableSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredNavigableSet<E>( checkNotNull(unfiltered), checkNotNull(predicate)); } @GwtIncompatible("NavigableSet") private static class FilteredNavigableSet<E> extends FilteredSortedSet<E> implements NavigableSet<E> { FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } NavigableSet<E> unfiltered() { return (NavigableSet<E>) unfiltered; } @Override @Nullable public E lower(E e) { return Iterators.getNext(headSet(e, false).descendingIterator(), null); } @Override @Nullable public E floor(E e) { return Iterators.getNext(headSet(e, true).descendingIterator(), null); } @Override public E ceiling(E e) { return Iterables.getFirst(tailSet(e, true), null); } @Override public E higher(E e) { return Iterables.getFirst(tailSet(e, false), null); } @Override public E pollFirst() { return Iterables.removeFirstMatching(unfiltered(), predicate); } @Override public E pollLast() { return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate); } @Override public NavigableSet<E> descendingSet() { return Sets.filter(unfiltered().descendingSet(), predicate); } @Override public Iterator<E> descendingIterator() { return Iterators.filter(unfiltered().descendingIterator(), predicate); } @Override public E last() { return descendingIterator().next(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return filter( unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return filter(unfiltered().headSet(toElement, inclusive), predicate); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return filter(unfiltered().tailSet(fromElement, inclusive), predicate); } } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct(ImmutableList.of( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C")))}</pre> * * <p>returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical * order for Cartesian products that you would get from nesting for loops: * <pre> {@code * * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * }}</pre> * * <p>Note that if any input set is empty, the Cartesian product will also be * empty. If no sets at all are provided (an empty list), the resulting * Cartesian product has one element, an empty list (counter-intuitive, but * mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets should appear in the resulting * lists * @param <B> any common base class shared by all axes (often just {@link * Object}) * @return the Cartesian product, as an immutable set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( List<? extends Set<? extends B>> sets) { return CartesianSet.create(sets); } /** * Returns every possible list that can be formed by choosing one element * from each of the given sets in order; the "n-ary * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: <pre> {@code * * Sets.cartesianProduct( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C"))}</pre> * * <p>returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical * order for Cartesian products that you would get from nesting for loops: * <pre> {@code * * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * }}</pre> * * <p>Note that if any input set is empty, the Cartesian product will also be * empty. If no sets at all are provided (an empty list), the resulting * Cartesian product has one element, an empty list (counter-intuitive, but * mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory * consumption is much smaller. When the cartesian set is constructed, the * input sets are merely copied. Only as the resulting set is iterated are the * individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that * the elements chosen from those sets should appear in the resulting * lists * @param <B> any common base class shared by all axes (often just {@link * Object}) * @return the Cartesian product, as an immutable set containing immutable * lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, * or any element of a provided set is null * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct( Set<? extends B>... sets) { return cartesianProduct(Arrays.asList(sets)); } private static final class CartesianSet<E> extends ForwardingCollection<List<E>> implements Set<List<E>> { private transient final ImmutableList<ImmutableSet<E>> axes; private transient final CartesianList<E> delegate; static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) { ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<ImmutableSet<E>>(sets.size()); for (Set<? extends E> set : sets) { ImmutableSet<E> copy = ImmutableSet.copyOf(set); if (copy.isEmpty()) { return ImmutableSet.of(); } axesBuilder.add(copy); } final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build(); ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() { @Override public int size() { return axes.size(); } @Override public List<E> get(int index) { return axes.get(index).asList(); } @Override boolean isPartialView() { return true; } }; return new CartesianSet<E>(axes, new CartesianList<E>(listAxes)); } private CartesianSet( ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) { this.axes = axes; this.delegate = delegate; } @Override protected Collection<List<E>> delegate() { return delegate; } @Override public boolean equals(@Nullable Object object) { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this if (object instanceof CartesianSet) { CartesianSet<?> that = (CartesianSet<?>) object; return this.axes.equals(that.axes); } return super.equals(object); } @Override public int hashCode() { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this // It's a weird formula, but tests prove it works. int adjust = size() - 1; for (int i = 0; i < axes.size(); i++) { adjust *= 31; adjust = ~~adjust; // in GWT, we have to deal with integer overflow carefully } int hash = 1; for (Set<E> axis : axes) { hash = 31 * hash + (size() / axis.size() * axis.hashCode()); hash = ~~hash; } hash += adjust; return ~~hash; } } /** * Returns the set of all possible subsets of {@code set}. For example, * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, * {1}, {2}, {1, 2}}}. * * <p>Elements appear in these subsets in the same iteration order as they * appeared in the input set. The order in which these subsets appear in the * outer set is undefined. Note that the power set of the empty set is not the * empty set, but a one-element set containing the empty set. * * <p>The returned set and its constituent sets use {@code equals} to decide * whether two elements are identical, even if the input set uses a different * concept of equivalence. * * <p><i>Performance notes:</i> while the power set of a set with size {@code * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the * power set is constructed, the input set is merely copied. Only as the * power set is iterated are the individual subsets created, and these subsets * themselves occupy only a small constant amount of memory. * * @param set the set of elements to construct a power set from * @return the power set, as an immutable set of immutable sets * @throws IllegalArgumentException if {@code set} has more than 30 unique * elements (causing the power set size to exceed the {@code int} range) * @throws NullPointerException if {@code set} is or contains {@code null} * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at * Wikipedia</a> * @since 4.0 */ @GwtCompatible(serializable = false) public static <E> Set<Set<E>> powerSet(Set<E> set) { return new PowerSet<E>(set); } private static final class SubSet<E> extends AbstractSet<E> { private final ImmutableMap<E, Integer> inputSet; private final int mask; SubSet(ImmutableMap<E, Integer> inputSet, int mask) { this.inputSet = inputSet; this.mask = mask; } @Override public Iterator<E> iterator() { return new UnmodifiableIterator<E>() { final ImmutableList<E> elements = inputSet.keySet().asList(); int remainingSetBits = mask; @Override public boolean hasNext() { return remainingSetBits != 0; } @Override public E next() { int index = Integer.numberOfTrailingZeros(remainingSetBits); if (index == 32) { throw new NoSuchElementException(); } remainingSetBits &= ~(1 << index); return elements.get(index); } }; } @Override public int size() { return Integer.bitCount(mask); } @Override public boolean contains(@Nullable Object o) { Integer index = inputSet.get(o); return index != null && (mask & (1 << index)) != 0; } } private static final class PowerSet<E> extends AbstractSet<Set<E>> { final ImmutableMap<E, Integer> inputSet; PowerSet(Set<E> input) { ImmutableMap.Builder<E, Integer> builder = ImmutableMap.builder(); int i = 0; for (E e : checkNotNull(input)) { builder.put(e, i++); } this.inputSet = builder.build(); checkArgument(inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size()); } @Override public int size() { return 1 << inputSet.size(); } @Override public boolean isEmpty() { return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIndexedListIterator<Set<E>>(size()) { @Override protected Set<E> get(final int setBits) { return new SubSet<E>(inputSet, setBits); } }; } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof Set) { Set<?> set = (Set<?>) obj; return inputSet.keySet().containsAll(set); } return false; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof PowerSet) { PowerSet<?> that = (PowerSet<?>) obj; return inputSet.equals(that.inputSet); } return super.equals(obj); } @Override public int hashCode() { /* * The sum of the sums of the hash codes in each subset is just the sum of * each input element's hash code times the number of sets that element * appears in. Each element appears in exactly half of the 2^n sets, so: */ return inputSet.keySet().hashCode() << (inputSet.size() - 1); } @Override public String toString() { return "powerSet(" + inputSet + ")"; } } /** * An implementation for {@link Set#hashCode()}. */ static int hashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; hashCode = ~~hashCode; // Needed to deal with unusual integer overflow in GWT. } return hashCode; } /** * An implementation for {@link Set#equals(Object)}. */ static boolean equalsImpl(Set<?> s, @Nullable Object object) { if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } } return false; } /** * Returns an unmodifiable view of the specified navigable set. This method * allows modules to provide users with "read-only" access to internal * navigable sets. Query operations on the returned set "read through" to the * specified set, and attempts to modify the returned set, whether direct or * via its collection views, result in an * {@code UnsupportedOperationException}. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param set the navigable set for which an unmodifiable view is to be * returned * @return an unmodifiable view of the specified navigable set * @since 12.0 */ @GwtIncompatible("NavigableSet") public static <E> NavigableSet<E> unmodifiableNavigableSet( NavigableSet<E> set) { if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) { return set; } return new UnmodifiableNavigableSet<E>(set); } @GwtIncompatible("NavigableSet") static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable { private final NavigableSet<E> delegate; UnmodifiableNavigableSet(NavigableSet<E> delegate) { this.delegate = checkNotNull(delegate); } @Override protected SortedSet<E> delegate() { return Collections.unmodifiableSortedSet(delegate); } @Override public E lower(E e) { return delegate.lower(e); } @Override public E floor(E e) { return delegate.floor(e); } @Override public E ceiling(E e) { return delegate.ceiling(e); } @Override public E higher(E e) { return delegate.higher(e); } @Override public E pollFirst() { throw new UnsupportedOperationException(); } @Override public E pollLast() { throw new UnsupportedOperationException(); } private transient UnmodifiableNavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { UnmodifiableNavigableSet<E> result = descendingSet; if (result == null) { result = descendingSet = new UnmodifiableNavigableSet<E>( delegate.descendingSet()); result.descendingSet = this; } return result; } @Override public Iterator<E> descendingIterator() { return Iterators.unmodifiableIterator(delegate.descendingIterator()); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return unmodifiableNavigableSet(delegate.subSet( fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return unmodifiableNavigableSet( delegate.tailSet(fromElement, inclusive)); } private static final long serialVersionUID = 0; } /** * Returns a synchronized (thread-safe) navigable set backed by the specified * navigable set. In order to guarantee serial access, it is critical that * <b>all</b> access to the backing navigable set is accomplished * through the returned navigable set (or its views). * * <p>It is imperative that the user manually synchronize on the returned * sorted set when iterating over it or any of its {@code descendingSet}, * {@code subSet}, {@code headSet}, or {@code tailSet} views. <pre> {@code * * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); * ... * synchronized (set) { * // Must be in the synchronized block * Iterator<E> it = set.iterator(); * while (it.hasNext()) { * foo(it.next()); * } * }}</pre> * * <p>or: <pre> {@code * * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); * NavigableSet<E> set2 = set.descendingSet().headSet(foo); * ... * synchronized (set) { // Note: set, not set2!!! * // Must be in the synchronized block * Iterator<E> it = set2.descendingIterator(); * while (it.hasNext()) * foo(it.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable set will be serializable if the specified * navigable set is serializable. * * @param navigableSet the navigable set to be "wrapped" in a synchronized * navigable set. * @return a synchronized view of the specified navigable set. * @since 13.0 */ @GwtIncompatible("NavigableSet") public static <E> NavigableSet<E> synchronizedNavigableSet( NavigableSet<E> navigableSet) { return Synchronized.navigableSet(navigableSet); } /** * Remove each element in an iterable from a set. */ static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= set.remove(iterator.next()); } return changed; } static boolean removeAllImpl(Set<?> set, Collection<?> collection) { checkNotNull(collection); // for GWT if (collection instanceof Multiset) { collection = ((Multiset<?>) collection).elementSet(); } /* * AbstractSet.removeAll(List) has quadratic behavior if the list size * is just less than the set's size. We augment the test by * assuming that sets have fast contains() performance, and other * collections don't. See * http://code.google.com/p/guava-libraries/issues/detail?id=1013 */ if (collection instanceof Set && collection.size() > set.size()) { return Iterators.removeAll(set.iterator(), collection); } else { return removeAllImpl(set, collection.iterator()); } } @GwtIncompatible("NavigableSet") static class DescendingSet<E> extends ForwardingNavigableSet<E> { private final NavigableSet<E> forward; DescendingSet(NavigableSet<E> forward) { this.forward = forward; } @Override protected NavigableSet<E> delegate() { return forward; } @Override public E lower(E e) { return forward.higher(e); } @Override public E floor(E e) { return forward.ceiling(e); } @Override public E ceiling(E e) { return forward.floor(e); } @Override public E higher(E e) { return forward.lower(e); } @Override public E pollFirst() { return forward.pollLast(); } @Override public E pollLast() { return forward.pollFirst(); } @Override public NavigableSet<E> descendingSet() { return forward; } @Override public Iterator<E> descendingIterator() { return forward.iterator(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return forward.tailSet(toElement, inclusive).descendingSet(); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return forward.headSet(fromElement, inclusive).descendingSet(); } @SuppressWarnings("unchecked") @Override public Comparator<? super E> comparator() { Comparator<? super E> forwardComparator = forward.comparator(); if (forwardComparator == null) { return (Comparator) Ordering.natural().reverse(); } else { return reverse(forwardComparator); } } // If we inline this, we get a javac error. private static <T> Ordering<T> reverse(Comparator<T> forward) { return Ordering.from(forward).reverse(); } @Override public E first() { return forward.last(); } @Override public SortedSet<E> headSet(E toElement) { return standardHeadSet(toElement); } @Override public E last() { return forward.first(); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return standardSubSet(fromElement, toElement); } @Override public SortedSet<E> tailSet(E fromElement) { return standardTailSet(fromElement); } @Override public Iterator<E> iterator() { return forward.descendingIterator(); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.NoSuchElementException; import java.util.Queue; /** * A queue which forwards all its method calls to another queue. Subclasses * should override one or more methods to modify the behavior of the backing * queue as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingQueue} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #offer} which can lead to unexpected behavior. In this case, you should * override {@code offer} as well, either providing your own implementation, or * delegating to the provided {@code standardOffer} method. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingQueue<E> extends ForwardingCollection<E> implements Queue<E> { /** Constructor for use by subclasses. */ protected ForwardingQueue() {} @Override protected abstract Queue<E> delegate(); @Override public boolean offer(E o) { return delegate().offer(o); } @Override public E poll() { return delegate().poll(); } @Override public E remove() { return delegate().remove(); } @Override public E peek() { return delegate().peek(); } @Override public E element() { return delegate().element(); } /** * A sensible definition of {@link #offer} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #offer} to forward * to this implementation. * * @since 7.0 */ protected boolean standardOffer(E e) { try { return add(e); } catch (IllegalStateException caught) { return false; } } /** * A sensible definition of {@link #peek} in terms of {@link #element}. If you * override {@link #element}, you may wish to override {@link #peek} to * forward to this implementation. * * @since 7.0 */ protected E standardPeek() { try { return element(); } catch (NoSuchElementException caught) { return null; } } /** * A sensible definition of {@link #poll} in terms of {@link #remove}. If you * override {@link #remove}, you may wish to override {@link #poll} to forward * to this implementation. * * @since 7.0 */ protected E standardPoll() { try { return remove(); } catch (NoSuchElementException caught) { return null; } } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Maps.EntryTransformer; import java.lang.reflect.Array; import java.util.Collections; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Hayward Chan */ @GwtCompatible(emulated = true) class Platform { /** * Returns a new array of the given length with the same type as a reference * array. * * @param reference any array of the desired type * @param length the length of the new array */ static <T> T[] newArray(T[] reference, int length) { Class<?> type = reference.getClass().getComponentType(); // the cast is safe because // result.getClass() == reference.getClass().getComponentType() @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(type, length); return result; } static <E> Set<E> newSetFromMap(Map<E, Boolean> map) { return Collections.newSetFromMap(map); } /** * Configures the given map maker to use weak keys, if possible; does nothing * otherwise (i.e., in GWT). This is sometimes acceptable, when only * server-side code could generate enough volume that reclamation becomes * important. */ static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker.weakKeys(); } static <K, V1, V2> SortedMap<K, V2> mapsTransformEntriesSortedMap( SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return (fromMap instanceof NavigableMap) ? Maps.transformEntries((NavigableMap<K, V1>) fromMap, transformer) : Maps.transformEntriesIgnoreNavigable(fromMap, transformer); } static <K, V> SortedMap<K, V> mapsAsMapSortedSet(SortedSet<K> set, Function<? super K, V> function) { return (set instanceof NavigableSet) ? Maps.asMap((NavigableSet<K>) set, function) : Maps.asMapSortedIgnoreNavigable(set, function); } static <E> SortedSet<E> setsFilterSortedSet(SortedSet<E> set, Predicate<? super E> predicate) { return (set instanceof NavigableSet) ? Sets.filter((NavigableSet<E>) set, predicate) : Sets.filterSortedIgnoreNavigable(set, predicate); } static <K, V> SortedMap<K, V> mapsFilterSortedMap(SortedMap<K, V> map, Predicate<? super Map.Entry<K, V>> predicate) { return (map instanceof NavigableMap) ? Maps.filterEntries((NavigableMap<K, V>) map, predicate) : Maps.filterSortedIgnoreNavigable(map, predicate); } private Platform() {} }
Java
/* * 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 com.google.common.collect.MapConstraints.ConstrainedMap; import com.google.common.primitives.Primitives; import java.util.HashMap; import java.util.Map; /** * A mutable class-to-instance map backed by an arbitrary user-provided map. * See also {@link ImmutableClassToInstanceMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#ClassToInstanceMap"> * {@code ClassToInstanceMap}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ public final class MutableClassToInstanceMap<B> extends ConstrainedMap<Class<? extends B>, B> implements ClassToInstanceMap<B> { /** * Returns a new {@code MutableClassToInstanceMap} instance backed by a {@link * HashMap} using the default initial capacity and load factor. */ public static <B> MutableClassToInstanceMap<B> create() { return new MutableClassToInstanceMap<B>( new HashMap<Class<? extends B>, B>()); } /** * Returns a new {@code MutableClassToInstanceMap} instance backed by a given * empty {@code backingMap}. The caller surrenders control of the backing map, * and thus should not allow any direct references to it to remain accessible. */ public static <B> MutableClassToInstanceMap<B> create( Map<Class<? extends B>, B> backingMap) { return new MutableClassToInstanceMap<B>(backingMap); } private MutableClassToInstanceMap(Map<Class<? extends B>, B> delegate) { super(delegate, VALUE_CAN_BE_CAST_TO_KEY); } private static final MapConstraint<Class<?>, Object> VALUE_CAN_BE_CAST_TO_KEY = new MapConstraint<Class<?>, Object>() { @Override public void checkKeyValue(Class<?> key, Object value) { cast(key, value); } }; @Override public <T extends B> T putInstance(Class<T> type, T value) { return cast(type, put(type, value)); } @Override public <T extends B> T getInstance(Class<T> type) { return cast(type, get(type)); } private static <B, T extends B> T cast(Class<T> type, B value) { return Primitives.wrap(type).cast(value); } private static final long serialVersionUID = 0; }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** * @see com.google.common.collect.Maps#immutableEntry(Object, Object) */ @GwtCompatible(serializable = true) class ImmutableEntry<K, V> extends AbstractMapEntry<K, V> implements Serializable { final K key; final V value; ImmutableEntry(@Nullable K key, @Nullable V value) { this.key = key; this.value = value; } @Nullable @Override public final K getKey() { return key; } @Nullable @Override public final V getValue() { return value; } @Override public final V setValue(V value) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * A map entry which forwards all its method calls to another map entry. * Subclasses should override one or more methods to modify the behavior of the * backing map entry as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingMapEntry} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #getValue} alone <i>will not</i> change the behavior of * {@link #equals}, which can lead to unexpected behavior. In this case, you * should override {@code equals} as well, either providing your own * implementation, or delegating to the provided {@code standardEquals} method. * * <p>Each of the {@code standard} methods, where appropriate, use {@link * Objects#equal} to test equality for both keys and values. This may not be * the desired behavior for map implementations that use non-standard notions of * key equality, such as the entry of a {@code SortedMap} whose comparator is * not consistent with {@code equals}. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingMapEntry<K, V> extends ForwardingObject implements Map.Entry<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingMapEntry() {} @Override protected abstract Map.Entry<K, V> delegate(); @Override public K getKey() { return delegate().getKey(); } @Override public V getValue() { return delegate().getValue(); } @Override public V setValue(V value) { return delegate().setValue(value); } @Override public boolean equals(@Nullable Object object) { return delegate().equals(object); } @Override public int hashCode() { return delegate().hashCode(); } /** * A sensible definition of {@link #equals(Object)} in terms of {@link * #getKey()} and {@link #getValue()}. If you override either of these * methods, you may wish to override {@link #equals(Object)} to forward to * this implementation. * * @since 7.0 */ protected boolean standardEquals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } /** * A sensible definition of {@link #hashCode()} in terms of {@link #getKey()} * and {@link #getValue()}. If you override either of these methods, you may * wish to override {@link #hashCode()} to forward to this implementation. * * @since 7.0 */ protected int standardHashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * A sensible definition of {@link #toString} in terms of {@link * #getKey} and {@link #getValue}. If you override either of these * methods, you may wish to override {@link #equals} to forward to this * implementation. * * @since 7.0 */ @Beta protected String standardToString() { return getKey() + "=" + getValue(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.Beta; import java.util.Iterator; import java.util.NavigableSet; import java.util.SortedSet; /** * A navigable set which forwards all its method calls to another navigable set. Subclasses should * override one or more methods to modify the behavior of the backing set as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingNavigableSet} forward <i>indiscriminately</i> * to the methods of the delegate. For example, overriding {@link #add} alone <i>will not</i> * change the behavior of {@link #addAll}, which can lead to unexpected behavior. In this case, you * should override {@code addAll} as well, either providing your own implementation, or delegating * to the provided {@code standardAddAll} method. * * <p>Each of the {@code standard} methods uses the set's comparator (or the natural ordering of * the elements, if there is no comparator) to test element equality. As a result, if the * comparator is not consistent with equals, some of the standard implementations may violate the * {@code Set} contract. * * <p>The {@code standard} methods and the collection views they return are not guaranteed to be * thread-safe, even when all of the methods that they depend on are thread-safe. * * @author Louis Wasserman * @since 12.0 */ public abstract class ForwardingNavigableSet<E> extends ForwardingSortedSet<E> implements NavigableSet<E> { /** Constructor for use by subclasses. */ protected ForwardingNavigableSet() {} @Override protected abstract NavigableSet<E> delegate(); @Override public E lower(E e) { return delegate().lower(e); } /** * A sensible definition of {@link #lower} in terms of the {@code descendingIterator} method of * {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may * wish to override {@link #lower} to forward to this implementation. */ protected E standardLower(E e) { return Iterators.getNext(headSet(e, false).descendingIterator(), null); } @Override public E floor(E e) { return delegate().floor(e); } /** * A sensible definition of {@link #floor} in terms of the {@code descendingIterator} method of * {@link #headSet(Object, boolean)}. If you override {@link #headSet(Object, boolean)}, you may * wish to override {@link #floor} to forward to this implementation. */ protected E standardFloor(E e) { return Iterators.getNext(headSet(e, true).descendingIterator(), null); } @Override public E ceiling(E e) { return delegate().ceiling(e); } /** * A sensible definition of {@link #ceiling} in terms of the {@code iterator} method of * {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may * wish to override {@link #ceiling} to forward to this implementation. */ protected E standardCeiling(E e) { return Iterators.getNext(tailSet(e, true).iterator(), null); } @Override public E higher(E e) { return delegate().higher(e); } /** * A sensible definition of {@link #higher} in terms of the {@code iterator} method of * {@link #tailSet(Object, boolean)}. If you override {@link #tailSet(Object, boolean)}, you may * wish to override {@link #higher} to forward to this implementation. */ protected E standardHigher(E e) { return Iterators.getNext(tailSet(e, false).iterator(), null); } @Override public E pollFirst() { return delegate().pollFirst(); } /** * A sensible definition of {@link #pollFirst} in terms of the {@code iterator} method. If you * override {@link #iterator} you may wish to override {@link #pollFirst} to forward to this * implementation. */ protected E standardPollFirst() { return Iterators.pollNext(iterator()); } @Override public E pollLast() { return delegate().pollLast(); } /** * A sensible definition of {@link #pollLast} in terms of the {@code descendingIterator} method. * If you override {@link #descendingIterator} you may wish to override {@link #pollLast} to * forward to this implementation. */ protected E standardPollLast() { return Iterators.pollNext(descendingIterator()); } protected E standardFirst() { return iterator().next(); } protected E standardLast() { return descendingIterator().next(); } @Override public NavigableSet<E> descendingSet() { return delegate().descendingSet(); } /** * A sensible implementation of {@link NavigableSet#descendingSet} in terms of the other methods * of {@link NavigableSet}, notably including {@link NavigableSet#descendingIterator}. * * <p>In many cases, you may wish to override {@link ForwardingNavigableSet#descendingSet} to * forward to this implementation or a subclass thereof. * * @since 12.0 */ @Beta protected class StandardDescendingSet extends Sets.DescendingSet<E> { /** Constructor for use by subclasses. */ public StandardDescendingSet() { super(ForwardingNavigableSet.this); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return delegate().subSet(fromElement, fromInclusive, toElement, toInclusive); } /** * A sensible definition of {@link #subSet(Object, boolean, Object, boolean)} in terms of the * {@code headSet} and {@code tailSet} methods. In many cases, you may wish to override * {@link #subSet(Object, boolean, Object, boolean)} to forward to this implementation. */ @Beta protected NavigableSet<E> standardSubSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return tailSet(fromElement, fromInclusive).headSet(toElement, toInclusive); } /** * A sensible definition of {@link #subSet(Object, Object)} in terms of the * {@link #subSet(Object, boolean, Object, boolean)} method. If you override * {@link #subSet(Object, boolean, Object, boolean)}, you may wish to override * {@link #subSet(Object, Object)} to forward to this implementation. */ @Override protected SortedSet<E> standardSubSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return delegate().headSet(toElement, inclusive); } /** * A sensible definition of {@link #headSet(Object)} in terms of the * {@link #headSet(Object, boolean)} method. If you override * {@link #headSet(Object, boolean)}, you may wish to override * {@link #headSet(Object)} to forward to this implementation. */ protected SortedSet<E> standardHeadSet(E toElement) { return headSet(toElement, false); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return delegate().tailSet(fromElement, inclusive); } /** * A sensible definition of {@link #tailSet(Object)} in terms of the * {@link #tailSet(Object, boolean)} method. If you override * {@link #tailSet(Object, boolean)}, you may wish to override * {@link #tailSet(Object)} to forward to this implementation. */ protected SortedSet<E> standardTailSet(E fromElement) { return tailSet(fromElement, true); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import java.util.ListIterator; /** * An iterator that transforms a backing list iterator; for internal use. This * avoids the object overhead of constructing a {@link Function} for internal * methods. * * @author Louis Wasserman */ @GwtCompatible abstract class TransformedListIterator<F, T> extends TransformedIterator<F, T> implements ListIterator<T> { TransformedListIterator(ListIterator<? extends F> backingIterator) { super(backingIterator); } private ListIterator<? extends F> backingIterator() { return Iterators.cast(backingIterator); } @Override public final boolean hasPrevious() { return backingIterator().hasPrevious(); } @Override public final T previous() { return transform(backingIterator().previous()); } @Override public final int nextIndex() { return backingIterator().nextIndex(); } @Override public final int previousIndex() { return backingIterator().previousIndex(); } @Override public void set(T element) { throw new UnsupportedOperationException(); } @Override public void add(T element) { throw new UnsupportedOperationException(); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Map.Entry; import javax.annotation.Nullable; /** * {@code entrySet()} implementation for {@link ImmutableMap}. * * @author Jesse Wilson * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) abstract class ImmutableMapEntrySet<K, V> extends ImmutableSet<Entry<K, V>> { ImmutableMapEntrySet() {} abstract ImmutableMap<K, V> map(); @Override public int size() { return map().size(); } @Override public boolean contains(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) object; V value = map().get(entry.getKey()); return value != null && value.equals(entry.getValue()); } return false; } @Override boolean isPartialView() { return map().isPartialView(); } @GwtIncompatible("serialization") @Override Object writeReplace() { return new EntrySetSerializedForm<K, V>(map()); } @GwtIncompatible("serialization") private static class EntrySetSerializedForm<K, V> implements Serializable { final ImmutableMap<K, V> map; EntrySetSerializedForm(ImmutableMap<K, V> map) { this.map = map; } Object readResolve() { return map.entrySet(); } private static final long serialVersionUID = 0; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; /** * An ordering which sorts iterables by comparing corresponding elements * pairwise. */ @GwtCompatible(serializable = true) final class LexicographicalOrdering<T> extends Ordering<Iterable<T>> implements Serializable { final Ordering<? super T> elementOrder; LexicographicalOrdering(Ordering<? super T> elementOrder) { this.elementOrder = elementOrder; } @Override public int compare( Iterable<T> leftIterable, Iterable<T> rightIterable) { Iterator<T> left = leftIterable.iterator(); Iterator<T> right = rightIterable.iterator(); while (left.hasNext()) { if (!right.hasNext()) { return LEFT_IS_GREATER; // because it's longer } int result = elementOrder.compare(left.next(), right.next()); if (result != 0) { return result; } } if (right.hasNext()) { return RIGHT_IS_GREATER; // because it's longer } return 0; } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof LexicographicalOrdering) { LexicographicalOrdering<?> that = (LexicographicalOrdering<?>) object; return this.elementOrder.equals(that.elementOrder); } return false; } @Override public int hashCode() { return elementOrder.hashCode() ^ 2075626741; // meaningless } @Override public String toString() { return elementOrder + ".lexicographical()"; } private static final long serialVersionUID = 0; }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedMap; import javax.annotation.Nullable; /** * A sorted map which forwards all its method calls to another sorted map. * Subclasses should override one or more methods to modify the behavior of * the backing sorted map as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><i>Warning:</i> The methods of {@code ForwardingSortedMap} forward * <i>indiscriminately</i> to the methods of the delegate. For example, * overriding {@link #put} alone <i>will not</i> change the behavior of {@link * #putAll}, which can lead to unexpected behavior. In this case, you should * override {@code putAll} as well, either providing your own implementation, or * delegating to the provided {@code standardPutAll} method. * * <p>Each of the {@code standard} methods, where appropriate, use the * comparator of the map to test equality for both keys and values, unlike * {@code ForwardingMap}. * * <p>The {@code standard} methods and the collection views they return are not * guaranteed to be thread-safe, even when all of the methods that they depend * on are thread-safe. * * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingSortedMap<K, V> extends ForwardingMap<K, V> implements SortedMap<K, V> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingSortedMap() {} @Override protected abstract SortedMap<K, V> delegate(); @Override public Comparator<? super K> comparator() { return delegate().comparator(); } @Override public K firstKey() { return delegate().firstKey(); } @Override public SortedMap<K, V> headMap(K toKey) { return delegate().headMap(toKey); } @Override public K lastKey() { return delegate().lastKey(); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return delegate().subMap(fromKey, toKey); } @Override public SortedMap<K, V> tailMap(K fromKey) { return delegate().tailMap(fromKey); } /** * A sensible implementation of {@link SortedMap#keySet} in terms of the methods of * {@code ForwardingSortedMap}. In many cases, you may wish to override * {@link ForwardingSortedMap#keySet} to forward to this implementation or a subclass thereof. * * @since 15.0 */ @Beta protected class StandardKeySet extends Maps.SortedKeySet<K, V> { /** Constructor for use by subclasses. */ public StandardKeySet() { super(ForwardingSortedMap.this); } } // unsafe, but worst case is a CCE is thrown, which callers will be expecting @SuppressWarnings("unchecked") private int unsafeCompare(Object k1, Object k2) { Comparator<? super K> comparator = comparator(); if (comparator == null) { return ((Comparable<Object>) k1).compareTo(k2); } else { return ((Comparator<Object>) comparator).compare(k1, k2); } } /** * A sensible definition of {@link #containsKey} in terms of the {@code * firstKey()} method of {@link #tailMap}. If you override {@link #tailMap}, * you may wish to override {@link #containsKey} to forward to this * implementation. * * @since 7.0 */ @Override @Beta protected boolean standardContainsKey(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Object ceilingKey = self.tailMap(key).firstKey(); return unsafeCompare(ceilingKey, key) == 0; } catch (ClassCastException e) { return false; } catch (NoSuchElementException e) { return false; } catch (NullPointerException e) { return false; } } /** * A sensible definition of {@link #remove} in terms of the {@code * iterator()} of the {@code entrySet()} of {@link #tailMap}. If you override * {@link #tailMap}, you may wish to override {@link #remove} to forward * to this implementation. * * @since 7.0 * @deprecated This implementation is extremely awkward, is rarely worthwhile, * and has been discovered to interact badly with * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6467933 in Java 6 * when used with certain null-friendly comparators. It is scheduled for * deletion in Guava 16.0. */ @Deprecated @Override @Beta protected V standardRemove(@Nullable Object key) { try { // any CCE will be caught @SuppressWarnings("unchecked") SortedMap<Object, V> self = (SortedMap<Object, V>) this; Iterator<Entry<Object, V>> entryIterator = self.tailMap(key).entrySet().iterator(); if (entryIterator.hasNext()) { Entry<Object, V> ceilingEntry = entryIterator.next(); if (unsafeCompare(ceilingEntry.getKey(), key) == 0) { V value = ceilingEntry.getValue(); entryIterator.remove(); return value; } } } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } return null; } /** * A sensible default implementation of {@link #subMap(Object, Object)} in * terms of {@link #headMap(Object)} and {@link #tailMap(Object)}. In some * situations, you may wish to override {@link #subMap(Object, Object)} to * forward to this implementation. * * @since 7.0 */ @Beta protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) { checkArgument(unsafeCompare(fromKey, toKey) <= 0, "fromKey must be <= toKey"); return tailMap(fromKey).headMap(toKey); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.Beta; import java.util.Map; import javax.annotation.Nullable; /** * A mapping from disjoint nonempty ranges to non-null values. Queries look up the value * associated with the range (if any) that contains a specified key. * * <p>In contrast to {@link RangeSet}, no "coalescing" is done of {@linkplain * Range#isConnected(Range) connected} ranges, even if they are mapped to the same value. * * @author Louis Wasserman * @since 14.0 */ @Beta public interface RangeMap<K extends Comparable, V> { /** * Returns the value associated with the specified key, or {@code null} if there is no * such value. * * <p>Specifically, if any range in this range map contains the specified key, the value * associated with that range is returned. */ @Nullable V get(K key); /** * Returns the range containing this key and its associated value, if such a range is present * in the range map, or {@code null} otherwise. */ @Nullable Map.Entry<Range<K>, V> getEntry(K key); /** * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the ranges * in this {@code RangeMap}. * * @throws NoSuchElementException if this range map is empty */ Range<K> span(); /** * Maps a range to a specified value (optional operation). * * <p>Specifically, after a call to {@code put(range, value)}, if * {@link Range#contains(Comparable) range.contains(k)}, then {@link #get(Comparable) get(k)} * will return {@code value}. * * <p>If {@code range} {@linkplain Range#isEmpty() is empty}, then this is a no-op. */ void put(Range<K> range, V value); /** * Puts all the associations from {@code rangeMap} into this range map (optional operation). */ void putAll(RangeMap<K, V> rangeMap); /** * Removes all associations from this range map (optional operation). */ void clear(); /** * Removes all associations from this range map in the specified range (optional operation). * * <p>If {@code !range.contains(k)}, {@link #get(Comparable) get(k)} will return the same result * before and after a call to {@code remove(range)}. If {@code range.contains(k)}, then * after a call to {@code remove(range)}, {@code get(k)} will return {@code null}. */ void remove(Range<K> range); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. * Modifications to this range map are guaranteed to read through to the returned {@code Map}. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. */ Map<Range<K>, V> asMapOfRanges(); /** * Returns a view of the part of this range map that intersects with {@code range}. * * <p>For example, if {@code rangeMap} had the entries * {@code [1, 5] => "foo", (6, 8) => "bar", (10, \u2025) => "baz"} * then {@code rangeMap.subRangeMap(Range.open(3, 12))} would return a range map * with the entries {@code (3, 5) => "foo", (6, 8) => "bar", (10, 12) => "baz"}. * * <p>The returned range map supports all optional operations that this range map supports, * except for {@code asMapOfRanges().iterator().remove()}. * * <p>The returned range map will throw an {@link IllegalArgumentException} on an attempt to * insert a range not {@linkplain Range#encloses(Range) enclosed} by {@code range}. */ RangeMap<K, V> subRangeMap(Range<K> range); /** * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an equivalent * {@link #asMapOfRanges()}. */ @Override boolean equals(@Nullable Object o); /** * Returns {@code asMapOfRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range map. */ @Override String toString(); }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A bimap (or "bidirectional map") is a map that preserves the uniqueness of * its values as well as that of its keys. This constraint enables bimaps to * support an "inverse view", which is another bimap containing the same entries * as this bimap but with reversed keys and values. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> * {@code BiMap}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface BiMap<K, V> extends Map<K, V> { // Modification Operations /** * {@inheritDoc} * * @throws IllegalArgumentException if the given value is already bound to a * different key in this bimap. The bimap will remain unmodified in this * event. To avoid this exception, call {@link #forcePut} instead. */ @Override V put(@Nullable K key, @Nullable V value); /** * An alternate form of {@code put} that silently removes any existing entry * with the value {@code value} before proceeding with the {@link #put} * operation. If the bimap previously contained the provided key-value * mapping, this method has no effect. * * <p>Note that a successful call to this method could cause the size of the * bimap to increase by one, stay the same, or even decrease by one. * * <p><b>Warning:</b> If an existing entry with this value is removed, the key * for that entry is discarded and not returned. * * @param key the key with which the specified value is to be associated * @param value the value to be associated with the specified key * @return the value which was previously associated with the key, which may * be {@code null}, or {@code null} if there was no previous entry */ V forcePut(@Nullable K key, @Nullable V value); // Bulk Operations /** * {@inheritDoc} * * <p><b>Warning:</b> the results of calling this method may vary depending on * the iteration order of {@code map}. * * @throws IllegalArgumentException if an attempt to {@code put} any * entry fails. Note that some map entries may have been added to the * bimap before the exception was thrown. */ @Override void putAll(Map<? extends K, ? extends V> map); // Views /** * {@inheritDoc} * * <p>Because a bimap has unique values, this method returns a {@link Set}, * instead of the {@link java.util.Collection} specified in the {@link Map} * interface. */ @Override Set<V> values(); /** * Returns the inverse view of this bimap, which maps each of this bimap's * values to its associated key. The two bimaps are backed by the same data; * any changes to one will appear in the other. * * <p><b>Note:</b>There is no guaranteed correspondence between the iteration * order of a bimap and that of its inverse. * * @return the inverse view of this bimap */ BiMap<V, K> inverse(); }
Java
/* * 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.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Comparator; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.annotation.Nullable; /** * Implementation of {@code Multimap} whose keys and values are ordered by * their natural ordering or by supplied comparators. In all cases, this * implementation uses {@link Comparable#compareTo} or {@link * Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparators or comparables used must be <i>consistent * with equals</i> as explained by the {@link Comparable} class specification. * Otherwise, the resulting multiset will violate the general contract of {@link * SetMultimap}, which it is specified in terms of {@link Object#equals}. * * <p>The collections returned by {@code keySet} and {@code asMap} iterate * through the keys according to the key comparator ordering or the natural * ordering of the keys. Similarly, {@code get}, {@code removeAll}, and {@code * replaceValues} return collections that iterate through the values according * to the value comparator ordering or the natural ordering of the values. The * collections generated by {@code entries}, {@code keys}, and {@code values} * iterate across the keys according to the above key ordering, and for each * key they iterate across the values according to the value ordering. * * <p>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. * * <p>Null keys and values are permitted (provided, of course, that the * respective comparators support them). All optional multimap methods are * supported, and all returned views are modifiable. * * <p>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 {@link * Multimaps#synchronizedSortedSetMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class TreeMultimap<K, V> extends AbstractSortedKeySortedSetMultimap<K, V> { private transient Comparator<? super K> keyComparator; private transient Comparator<? super V> valueComparator; /** * Creates an empty {@code TreeMultimap} ordered by the natural ordering of * its keys and values. */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create() { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural()); } /** * Creates an empty {@code TreeMultimap} instance using explicit comparators. * Neither comparator may be null; use {@link Ordering#natural()} to specify * natural order. * * @param keyComparator the comparator that determines the key ordering * @param valueComparator the comparator that determines the value ordering */ public static <K, V> TreeMultimap<K, V> create( Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { return new TreeMultimap<K, V>(checkNotNull(keyComparator), checkNotNull(valueComparator)); } /** * Constructs a {@code TreeMultimap}, ordered by the natural ordering of its * keys and values, with the same mappings as the specified multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K extends Comparable, V extends Comparable> TreeMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) { return new TreeMultimap<K, V>(Ordering.natural(), Ordering.natural(), multimap); } TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator) { super(new TreeMap<K, Collection<V>>(keyComparator)); this.keyComparator = keyComparator; this.valueComparator = valueComparator; } private TreeMultimap(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator, Multimap<? extends K, ? extends V> multimap) { this(keyComparator, valueComparator); putAll(multimap); } /** * {@inheritDoc} * * <p>Creates an empty {@code TreeSet} for a collection of values for one key. * * @return a new {@code TreeSet} containing a collection of values for one * key */ @Override SortedSet<V> createCollection() { return new TreeSet<V>(valueComparator); } @Override Collection<V> createCollection(@Nullable K key) { if (key == null) { keyComparator().compare(key, key); } return super.createCollection(key); } /** * Returns the comparator that orders the multimap keys. */ public Comparator<? super K> keyComparator() { return keyComparator; } @Override public Comparator<? super V> valueComparator() { return valueComparator; } /* * The following @GwtIncompatible methods override the methods in * AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM implementations, * which return SortedSets and SortedMaps. */ @Override @GwtIncompatible("NavigableMap") NavigableMap<K, Collection<V>> backingMap() { return (NavigableMap<K, Collection<V>>) super.backingMap(); } /** * @since 14.0 (present with return type {@code SortedSet} since 2.0) */ @Override @GwtIncompatible("NavigableSet") public NavigableSet<V> get(@Nullable K key) { return (NavigableSet<V>) super.get(key); } @Override @GwtIncompatible("NavigableSet") Collection<V> unmodifiableCollectionSubclass(Collection<V> collection) { return Sets.unmodifiableNavigableSet((NavigableSet<V>) collection); } @Override @GwtIncompatible("NavigableSet") Collection<V> wrapCollection(K key, Collection<V> collection) { return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null); } /** * {@inheritDoc} * * <p>Because a {@code TreeMultimap} has unique sorted keys, this method * returns a {@link NavigableSet}, instead of the {@link java.util.Set} specified * in the {@link Multimap} interface. * * @since 14.0 (present with return type {@code SortedSet} since 2.0) */ @Override @GwtIncompatible("NavigableSet") public NavigableSet<K> keySet() { return (NavigableSet<K>) super.keySet(); } @Override @GwtIncompatible("NavigableSet") NavigableSet<K> createKeySet() { return new NavigableKeySet(backingMap()); } /** * {@inheritDoc} * * <p>Because a {@code TreeMultimap} has unique sorted keys, this method * returns a {@link NavigableMap}, instead of the {@link java.util.Map} specified * in the {@link Multimap} interface. * * @since 14.0 (present with return type {@code SortedMap} since 2.0) */ @Override @GwtIncompatible("NavigableMap") public NavigableMap<K, Collection<V>> asMap() { return (NavigableMap<K, Collection<V>>) super.asMap(); } @Override @GwtIncompatible("NavigableMap") NavigableMap<K, Collection<V>> createAsMap() { return new NavigableAsMap(backingMap()); } /** * @serialData key comparator, value comparator, number of distinct keys, and * then for each distinct key: the key, number of values for that key, and * key values */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(keyComparator()); stream.writeObject(valueComparator()); Serialization.writeMultimap(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyComparator = checkNotNull((Comparator<? super K>) stream.readObject()); valueComparator = checkNotNull((Comparator<? super V>) stream.readObject()); setMap(new TreeMap<K, Collection<V>>(keyComparator)); Serialization.populateMultimap(this, stream); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.Set; /** * A skeleton implementation of a descending multiset. Only needs * {@code forwardMultiset()} and {@code entryIterator()}. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) abstract class DescendingMultiset<E> extends ForwardingMultiset<E> implements SortedMultiset<E> { abstract SortedMultiset<E> forwardMultiset(); private transient Comparator<? super E> comparator; @Override public Comparator<? super E> comparator() { Comparator<? super E> result = comparator; if (result == null) { return comparator = Ordering.from(forwardMultiset().comparator()).<E>reverse(); } return result; } private transient NavigableSet<E> elementSet; @Override public NavigableSet<E> elementSet() { NavigableSet<E> result = elementSet; if (result == null) { return elementSet = new SortedMultisets.NavigableElementSet<E>(this); } return result; } @Override public Entry<E> pollFirstEntry() { return forwardMultiset().pollLastEntry(); } @Override public Entry<E> pollLastEntry() { return forwardMultiset().pollFirstEntry(); } @Override public SortedMultiset<E> headMultiset(E toElement, BoundType boundType) { return forwardMultiset().tailMultiset(toElement, boundType) .descendingMultiset(); } @Override public SortedMultiset<E> subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); } @Override public SortedMultiset<E> tailMultiset(E fromElement, BoundType boundType) { return forwardMultiset().headMultiset(fromElement, boundType) .descendingMultiset(); } @Override protected Multiset<E> delegate() { return forwardMultiset(); } @Override public SortedMultiset<E> descendingMultiset() { return forwardMultiset(); } @Override public Entry<E> firstEntry() { return forwardMultiset().lastEntry(); } @Override public Entry<E> lastEntry() { return forwardMultiset().firstEntry(); } abstract Iterator<Entry<E>> entryIterator(); private transient Set<Entry<E>> entrySet; @Override public Set<Entry<E>> entrySet() { Set<Entry<E>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } Set<Entry<E>> createEntrySet() { return new Multisets.EntrySet<E>() { @Override Multiset<E> multiset() { return DescendingMultiset.this; } @Override public Iterator<Entry<E>> iterator() { return entryIterator(); } @Override public int size() { return forwardMultiset().entrySet().size(); } }; } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return entrySet().toString(); } }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * A constraint on the keys and values that may be added to a {@code Map} or * {@code Multimap}. For example, {@link MapConstraints#notNull()}, which * prevents a map from including any null keys or values, could be implemented * like this: <pre> {@code * * public void checkKeyValue(Object key, Object value) { * if (key == null || value == null) { * throw new NullPointerException(); * } * }}</pre> * * <p>In order to be effective, constraints should be deterministic; that is, they * should not depend on state that can change (such as external state, random * variables, and time) and should only depend on the value of the passed-in key * and value. A non-deterministic constraint cannot reliably enforce that all * the collection's elements meet the constraint, since the constraint is only * enforced when elements are added. * * @author Mike Bostock * @see MapConstraints * @see Constraint * @since 3.0 */ @GwtCompatible @Beta public interface MapConstraint<K, V> { /** * Throws a suitable {@code RuntimeException} if the specified key or value is * illegal. Typically this is either a {@link NullPointerException}, an * {@link IllegalArgumentException}, or a {@link ClassCastException}, though * an application-specific exception class may be used if appropriate. */ void checkKeyValue(@Nullable K key, @Nullable V value); /** * Returns a brief human readable description of this constraint, such as * "Not null". */ @Override String toString(); }
Java
/* * 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. */ /** * This package contains generic collection interfaces and implementations, and * other utilities for working with collections. It is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <h2>Collection Types</h2> * * <dl> * <dt>{@link com.google.common.collect.BiMap} * <dd>An extension of {@link java.util.Map} that guarantees the uniqueness of * its values as well as that of its keys. This is sometimes called an * "invertible map," since the restriction on values enables it to support * an {@linkplain com.google.common.collect.BiMap#inverse inverse view} -- * which is another instance of {@code BiMap}. * * <dt>{@link com.google.common.collect.Multiset} * <dd>An extension of {@link java.util.Collection} that may contain duplicate * values like a {@link java.util.List}, yet has order-independent equality * like a {@link java.util.Set}. One typical use for a multiset is to * represent a histogram. * * <dt>{@link com.google.common.collect.Multimap} * <dd>A new type, which is similar to {@link java.util.Map}, but may contain * multiple entries with the same key. Some behaviors of * {@link com.google.common.collect.Multimap} are left unspecified and are * provided only by the subtypes mentioned below. * * <dt>{@link com.google.common.collect.ListMultimap} * <dd>An extension of {@link com.google.common.collect.Multimap} which permits * duplicate entries, supports random access of values for a particular key, * and has <i>partially order-dependent equality</i> as defined by * {@link com.google.common.collect.ListMultimap#equals(Object)}. {@code * ListMultimap} takes its name from the fact that the {@linkplain * com.google.common.collect.ListMultimap#get collection of values} * associated with a given key fulfills the {@link java.util.List} contract. * * <dt>{@link com.google.common.collect.SetMultimap} * <dd>An extension of {@link com.google.common.collect.Multimap} which has * order-independent equality and does not allow duplicate entries; that is, * while a key may appear twice in a {@code SetMultimap}, each must map to a * different value. {@code SetMultimap} takes its name from the fact that * the {@linkplain com.google.common.collect.SetMultimap#get collection of * values} associated with a given key fulfills the {@link java.util.Set} * contract. * * <dt>{@link com.google.common.collect.SortedSetMultimap} * <dd>An extension of {@link com.google.common.collect.SetMultimap} for which * the {@linkplain com.google.common.collect.SortedSetMultimap#get * collection values} associated with a given key is a * {@link java.util.SortedSet}. * * <dt>{@link com.google.common.collect.Table} * <dd>A new type, which is similar to {@link java.util.Map}, but which indexes * its values by an ordered pair of keys, a row key and column key. * * <dt>{@link com.google.common.collect.ClassToInstanceMap} * <dd>An extension of {@link java.util.Map} that associates a raw type with an * instance of that type. * </dl> * * <h2>Collection Implementations</h2> * * <h3>of {@link java.util.List}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableList} * </ul> * * <h3>of {@link java.util.Set}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableSet} * <li>{@link com.google.common.collect.ImmutableSortedSet} * <li>{@link com.google.common.collect.ContiguousSet} (see {@code Range}) * </ul> * * <h3>of {@link java.util.Map}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMap} * <li>{@link com.google.common.collect.ImmutableSortedMap} * <li>{@link com.google.common.collect.MapMaker} * </ul> * * <h3>of {@link com.google.common.collect.BiMap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableBiMap} * <li>{@link com.google.common.collect.HashBiMap} * <li>{@link com.google.common.collect.EnumBiMap} * <li>{@link com.google.common.collect.EnumHashBiMap} * </ul> * * <h3>of {@link com.google.common.collect.Multiset}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMultiset} * <li>{@link com.google.common.collect.HashMultiset} * <li>{@link com.google.common.collect.LinkedHashMultiset} * <li>{@link com.google.common.collect.TreeMultiset} * <li>{@link com.google.common.collect.EnumMultiset} * <li>{@link com.google.common.collect.ConcurrentHashMultiset} * </ul> * * <h3>of {@link com.google.common.collect.Multimap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableMultimap} * <li>{@link com.google.common.collect.ImmutableListMultimap} * <li>{@link com.google.common.collect.ImmutableSetMultimap} * <li>{@link com.google.common.collect.ArrayListMultimap} * <li>{@link com.google.common.collect.HashMultimap} * <li>{@link com.google.common.collect.TreeMultimap} * <li>{@link com.google.common.collect.LinkedHashMultimap} * <li>{@link com.google.common.collect.LinkedListMultimap} * </ul> * * <h3>of {@link com.google.common.collect.Table}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableTable} * <li>{@link com.google.common.collect.ArrayTable} * <li>{@link com.google.common.collect.HashBasedTable} * <li>{@link com.google.common.collect.TreeBasedTable} * </ul> * * <h3>of {@link com.google.common.collect.ClassToInstanceMap}</h3> * <ul> * <li>{@link com.google.common.collect.ImmutableClassToInstanceMap} * <li>{@link com.google.common.collect.MutableClassToInstanceMap} * </ul> * * <h2>Classes of static utility methods</h2> * * <ul> * <li>{@link com.google.common.collect.Collections2} * <li>{@link com.google.common.collect.Iterators} * <li>{@link com.google.common.collect.Iterables} * <li>{@link com.google.common.collect.Lists} * <li>{@link com.google.common.collect.Maps} * <li>{@link com.google.common.collect.Queues} * <li>{@link com.google.common.collect.Sets} * <li>{@link com.google.common.collect.Multisets} * <li>{@link com.google.common.collect.Multimaps} * <li>{@link com.google.common.collect.Tables} * <li>{@link com.google.common.collect.ObjectArrays} * </ul> * * <h2>Comparison</h2> * * <ul> * <li>{@link com.google.common.collect.Ordering} * <li>{@link com.google.common.collect.ComparisonChain} * </ul> * * <h2>Abstract implementations</h2> * * <ul> * <li>{@link com.google.common.collect.AbstractIterator} * <li>{@link com.google.common.collect.AbstractSequentialIterator} * <li>{@link com.google.common.collect.ImmutableCollection} * <li>{@link com.google.common.collect.UnmodifiableIterator} * <li>{@link com.google.common.collect.UnmodifiableListIterator} * </ul> * * <h2>Ranges</h2> * * <ul> * <li>{@link com.google.common.collect.Range} * <li>{@link com.google.common.collect.RangeMap} * <li>{@link com.google.common.collect.DiscreteDomain} * <li>{@link com.google.common.collect.ContiguousSet} * </ul> * * <h2>Other</h2> * * <ul> * <li>{@link com.google.common.collect.Interner}, * {@link com.google.common.collect.Interners} * <li>{@link com.google.common.collect.Constraint}, * {@link com.google.common.collect.Constraints} * <li>{@link com.google.common.collect.MapConstraint}, * {@link com.google.common.collect.MapConstraints} * <li>{@link com.google.common.collect.MapDifference}, * {@link com.google.common.collect.SortedMapDifference} * <li>{@link com.google.common.collect.MinMaxPriorityQueue} * <li>{@link com.google.common.collect.PeekingIterator} * </ul> * * <h2>Forwarding collections</h2> * * <ul> * <li>{@link com.google.common.collect.ForwardingCollection} * <li>{@link com.google.common.collect.ForwardingConcurrentMap} * <li>{@link com.google.common.collect.ForwardingIterator} * <li>{@link com.google.common.collect.ForwardingList} * <li>{@link com.google.common.collect.ForwardingListIterator} * <li>{@link com.google.common.collect.ForwardingListMultimap} * <li>{@link com.google.common.collect.ForwardingMap} * <li>{@link com.google.common.collect.ForwardingMapEntry} * <li>{@link com.google.common.collect.ForwardingMultimap} * <li>{@link com.google.common.collect.ForwardingMultiset} * <li>{@link com.google.common.collect.ForwardingNavigableMap} * <li>{@link com.google.common.collect.ForwardingNavigableSet} * <li>{@link com.google.common.collect.ForwardingObject} * <li>{@link com.google.common.collect.ForwardingQueue} * <li>{@link com.google.common.collect.ForwardingSet} * <li>{@link com.google.common.collect.ForwardingSetMultimap} * <li>{@link com.google.common.collect.ForwardingSortedMap} * <li>{@link com.google.common.collect.ForwardingSortedMultiset} * <li>{@link com.google.common.collect.ForwardingSortedSet} * <li>{@link com.google.common.collect.ForwardingSortedSetMultimap} * <li>{@link com.google.common.collect.ForwardingTable} * </ul> */ @javax.annotation.ParametersAreNonnullByDefault package com.google.common.collect;
Java
/* * 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.checkPositionIndex; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.unmodifiableList; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * An implementation of {@code ListMultimap} that supports deterministic * iteration order for both keys and values. The iteration order is preserved * across non-distinct key values. For example, for the following multimap * definition: <pre> {@code * * Multimap<K, V> multimap = LinkedListMultimap.create(); * multimap.put(key1, foo); * multimap.put(key2, bar); * multimap.put(key1, baz);}</pre> * * ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]}, * and similarly for {@link #entries()}. Unlike {@link LinkedHashMultimap}, the * iteration order is kept consistent between keys, entries and values. For * example, calling: <pre> {@code * * map.remove(key1, foo);}</pre> * * <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the * key iteration order to {@code [key2, key1]}. The {@link #entries()} iterator * returns mutable map entries, and {@link #replaceValues} attempts to preserve * iteration order as much as possible. * * <p>The collections returned by {@link #keySet()} and {@link #asMap} iterate * through the keys in the order they were first added to the multimap. * Similarly, {@link #get}, {@link #removeAll}, and {@link #replaceValues} * return collections that iterate through the values in the order they were * added. The collections generated by {@link #entries()}, {@link #keys()}, and * {@link #values} iterate across the key-value mappings in the order they were * added to the multimap. * * <p>The {@link #values()} and {@link #entries()} methods both return a * {@code List}, instead of the {@code Collection} specified by the {@link * ListMultimap} interface. * * <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()}, * {@link #values}, {@link #entries()}, and {@link #asMap} return collections * that are views of the multimap. If the multimap is modified while an * iteration over any of those collections is in progress, except through the * iterator's methods, the results of the iteration are undefined. * * <p>Keys and values may be null. All optional multimap methods are supported, * and all returned views are modifiable. * * <p>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 {@link * Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public class LinkedListMultimap<K, V> extends AbstractMultimap<K, V> implements ListMultimap<K, V>, Serializable { /* * Order is maintained using a linked list containing all key-value pairs. In * addition, a series of disjoint linked lists of "siblings", each containing * the values for a specific key, is used to implement {@link * ValueForKeyIterator} in constant time. */ private static final class Node<K, V> extends AbstractMapEntry<K, V> { final K key; V value; Node<K, V> next; // the next node (with any key) Node<K, V> previous; // the previous node (with any key) Node<K, V> nextSibling; // the next node with the same key Node<K, V> previousSibling; // the previous node with the same key Node(@Nullable K key, @Nullable V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(@Nullable V newValue) { V result = value; this.value = newValue; return result; } } private static class KeyList<K, V> { Node<K, V> head; Node<K, V> tail; int count; KeyList(Node<K, V> firstNode) { this.head = firstNode; this.tail = firstNode; firstNode.previousSibling = null; firstNode.nextSibling = null; this.count = 1; } } private transient Node<K, V> head; // the head for all keys private transient Node<K, V> tail; // the tail for all keys private transient Map<K, KeyList<K, V>> keyToKeyList; private transient int size; /* * Tracks modifications to keyToKeyList so that addition or removal of keys invalidates * preexisting iterators. This does *not* track simple additions and removals of values * that are not the first to be added or last to be removed for their key. */ private transient int modCount; /** * Creates a new, empty {@code LinkedListMultimap} with the default initial * capacity. */ public static <K, V> LinkedListMultimap<K, V> create() { return new LinkedListMultimap<K, V>(); } /** * Constructs an empty {@code LinkedListMultimap} with enough capacity to hold * the specified number of keys without rehashing. * * @param expectedKeys the expected number of distinct keys * @throws IllegalArgumentException if {@code expectedKeys} is negative */ public static <K, V> LinkedListMultimap<K, V> create(int expectedKeys) { return new LinkedListMultimap<K, V>(expectedKeys); } /** * Constructs a {@code LinkedListMultimap} with the same mappings as the * specified {@code Multimap}. The new multimap has the same * {@link Multimap#entries()} iteration order as the input multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K, V> LinkedListMultimap<K, V> create( Multimap<? extends K, ? extends V> multimap) { return new LinkedListMultimap<K, V>(multimap); } LinkedListMultimap() { keyToKeyList = Maps.newHashMap(); } private LinkedListMultimap(int expectedKeys) { keyToKeyList = new HashMap<K, KeyList<K, V>>(expectedKeys); } private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size()); putAll(multimap); } /** * Adds a new node for the specified key-value pair before the specified * {@code nextSibling} element, or at the end of the list if {@code * nextSibling} is null. Note: if {@code nextSibling} is specified, it MUST be * for an node for the same {@code key}! */ private Node<K, V> addNode( @Nullable K key, @Nullable V value, @Nullable Node<K, V> nextSibling) { Node<K, V> node = new Node<K, V>(key, value); if (head == null) { // empty list head = tail = node; keyToKeyList.put(key, new KeyList<K, V>(node)); modCount++; } else if (nextSibling == null) { // non-empty list, add to tail tail.next = node; node.previous = tail; tail = node; KeyList<K, V> keyList = keyToKeyList.get(key); if (keyList == null) { keyToKeyList.put(key, keyList = new KeyList<K, V>(node)); modCount++; } else { keyList.count++; Node<K, V> keyTail = keyList.tail; keyTail.nextSibling = node; node.previousSibling = keyTail; keyList.tail = node; } } else { // non-empty list, insert before nextSibling KeyList<K, V> keyList = keyToKeyList.get(key); keyList.count++; node.previous = nextSibling.previous; node.previousSibling = nextSibling.previousSibling; node.next = nextSibling; node.nextSibling = nextSibling; if (nextSibling.previousSibling == null) { // nextSibling was key head keyToKeyList.get(key).head = node; } else { nextSibling.previousSibling.nextSibling = node; } if (nextSibling.previous == null) { // nextSibling was head head = node; } else { nextSibling.previous.next = node; } nextSibling.previous = node; nextSibling.previousSibling = node; } size++; return node; } /** * Removes the specified node from the linked list. This method is only * intended to be used from the {@code Iterator} classes. See also {@link * LinkedListMultimap#removeAllNodes(Object)}. */ private void removeNode(Node<K, V> node) { if (node.previous != null) { node.previous.next = node.next; } else { // node was head head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { // node was tail tail = node.previous; } if (node.previousSibling == null && node.nextSibling == null) { KeyList<K, V> keyList = keyToKeyList.remove(node.key); keyList.count = 0; modCount++; } else { KeyList<K, V> keyList = keyToKeyList.get(node.key); keyList.count--; if (node.previousSibling == null) { keyList.head = node.nextSibling; } else { node.previousSibling.nextSibling = node.nextSibling; } if (node.nextSibling == null) { keyList.tail = node.previousSibling; } else { node.nextSibling.previousSibling = node.previousSibling; } } size--; } /** Removes all nodes for the specified key. */ private void removeAllNodes(@Nullable Object key) { Iterators.clear(new ValueForKeyIterator(key)); } /** Helper method for verifying that an iterator element is present. */ private static void checkElement(@Nullable Object node) { if (node == null) { throw new NoSuchElementException(); } } /** An {@code Iterator} over all nodes. */ private class NodeIterator implements ListIterator<Entry<K, V>> { int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; int expectedModCount = modCount; NodeIterator(int index) { int size = size(); checkPositionIndex(index, size); if (index >= (size / 2)) { previous = tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = head; while (index-- > 0) { next(); } } current = null; } private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @Override public Node<K, V> next() { checkForConcurrentModification(); checkElement(next); previous = current = next; next = next.next; nextIndex++; return current; } @Override public void remove() { checkForConcurrentModification(); checkState(current != null); if (current != next) { // after call to next() previous = current.previous; nextIndex--; } else { // after call to previous() next = current.next; } removeNode(current); current = null; expectedModCount = modCount; } @Override public boolean hasPrevious() { checkForConcurrentModification(); return previous != null; } @Override public Node<K, V> previous() { checkForConcurrentModification(); checkElement(previous); next = current = previous; previous = previous.previous; nextIndex--; return current; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void set(Entry<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Entry<K, V> e) { throw new UnsupportedOperationException(); } void setValue(V value) { checkState(current != null); current.value = value; } } /** An {@code Iterator} over distinct keys in key head order. */ private class DistinctKeyIterator implements Iterator<K> { final Set<K> seenKeys = Sets.<K>newHashSetWithExpectedSize(keySet().size()); Node<K, V> next = head; Node<K, V> current; int expectedModCount = modCount; private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @Override public K next() { checkForConcurrentModification(); checkElement(next); current = next; seenKeys.add(current.key); do { // skip ahead to next unseen key next = next.next; } while ((next != null) && !seenKeys.add(next.key)); return current.key; } @Override public void remove() { checkForConcurrentModification(); checkState(current != null); removeAllNodes(current.key); current = null; expectedModCount = modCount; } } /** A {@code ListIterator} over values for a specified key. */ private class ValueForKeyIterator implements ListIterator<V> { final Object key; int nextIndex; Node<K, V> next; Node<K, V> current; Node<K, V> previous; /** Constructs a new iterator over all values for the specified key. */ ValueForKeyIterator(@Nullable Object key) { this.key = key; KeyList<K, V> keyList = keyToKeyList.get(key); next = (keyList == null) ? null : keyList.head; } /** * Constructs a new iterator over all values for the specified key starting * at the specified index. This constructor is optimized so that it starts * at either the head or the tail, depending on which is closer to the * specified index. This allows adds to the tail to be done in constant * time. * * @throws IndexOutOfBoundsException if index is invalid */ public ValueForKeyIterator(@Nullable Object key, int index) { KeyList<K, V> keyList = keyToKeyList.get(key); int size = (keyList == null) ? 0 : keyList.count; checkPositionIndex(index, size); if (index >= (size / 2)) { previous = (keyList == null) ? null : keyList.tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = (keyList == null) ? null : keyList.head; while (index-- > 0) { next(); } } this.key = key; current = null; } @Override public boolean hasNext() { return next != null; } @Override public V next() { checkElement(next); previous = current = next; next = next.nextSibling; nextIndex++; return current.value; } @Override public boolean hasPrevious() { return previous != null; } @Override public V previous() { checkElement(previous); next = current = previous; previous = previous.previousSibling; nextIndex--; return current.value; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkState(current != null); if (current != next) { // after call to next() previous = current.previousSibling; nextIndex--; } else { // after call to previous() next = current.nextSibling; } removeNode(current); current = null; } @Override public void set(V value) { checkState(current != null); current.value = value; } @Override @SuppressWarnings("unchecked") public void add(V value) { previous = addNode((K) key, value, next); nextIndex++; current = null; } } // Query Operations @Override public int size() { return size; } @Override public boolean isEmpty() { return head == null; } @Override public boolean containsKey(@Nullable Object key) { return keyToKeyList.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } // Modification Operations /** * Stores a key-value pair in the multimap. * * @param key key to store in the multimap * @param value value to store in the multimap * @return {@code true} always */ @Override public boolean put(@Nullable K key, @Nullable V value) { addNode(key, value, null); return true; } // Bulk Operations /** * {@inheritDoc} * * <p>If any entries for the specified {@code key} already exist in the * multimap, their values are changed in-place without affecting the iteration * order. * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { List<V> oldValues = getCopy(key); ListIterator<V> keyValues = new ValueForKeyIterator(key); Iterator<? extends V> newValues = values.iterator(); // Replace existing values, if any. while (keyValues.hasNext() && newValues.hasNext()) { keyValues.next(); keyValues.set(newValues.next()); } // Remove remaining old values, if any. while (keyValues.hasNext()) { keyValues.next(); keyValues.remove(); } // Add remaining new values, if any. while (newValues.hasNext()) { keyValues.add(newValues.next()); } return oldValues; } private List<V> getCopy(@Nullable Object key) { return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); } /** * {@inheritDoc} * * <p>The returned list is immutable and implements * {@link java.util.RandomAccess}. */ @Override public List<V> removeAll(@Nullable Object key) { List<V> oldValues = getCopy(key); removeAllNodes(key); return oldValues; } @Override public void clear() { head = null; tail = null; keyToKeyList.clear(); size = 0; modCount++; } // Views /** * {@inheritDoc} * * <p>If the multimap is modified while an iteration over the list is in * progress (except through the iterator's own {@code add}, {@code set} or * {@code remove} operations) the results of the iteration are undefined. * * <p>The returned list is not serializable and does not have random access. */ @Override public List<V> get(final @Nullable K key) { return new AbstractSequentialList<V>() { @Override public int size() { KeyList<K, V> keyList = keyToKeyList.get(key); return (keyList == null) ? 0 : keyList.count; } @Override public ListIterator<V> listIterator(int index) { return new ValueForKeyIterator(key, index); } }; } @Override Set<K> createKeySet() { return new Sets.ImprovedAbstractSet<K>() { @Override public int size() { return keyToKeyList.size(); } @Override public Iterator<K> iterator() { return new DistinctKeyIterator(); } @Override public boolean contains(Object key) { // for performance return containsKey(key); } @Override public boolean remove(Object o) { // for performance return !LinkedListMultimap.this.removeAll(o).isEmpty(); } }; } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values * in the order they were added to the multimap. Because the values may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. */ @Override public List<V> values() { return (List<V>) super.values(); } @Override List<V> createValues() { return new AbstractSequentialList<V>() { @Override public int size() { return size; } @Override public ListIterator<V> listIterator(int index) { final NodeIterator nodeItr = new NodeIterator(index); return new TransformedListIterator<Entry<K, V>, V>(nodeItr) { @Override V transform(Entry<K, V> entry) { return entry.getValue(); } @Override public void set(V value) { nodeItr.setValue(value); } }; } }; } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the entries * in the order they were added to the multimap. Because the entries may have * duplicates and follow the insertion ordering, this method returns a {@link * List}, instead of the {@link Collection} specified in the {@link * ListMultimap} interface. * * <p>An entry's {@link Entry#getKey} method always returns the same key, * regardless of what happens subsequently. As long as the corresponding * key-value mapping is not removed from the multimap, {@link Entry#getValue} * returns the value from the multimap, which may change over time, and {@link * Entry#setValue} modifies that value. Removing the mapping from the * multimap does not alter the value returned by {@code getValue()}, though a * subsequent {@code setValue()} call won't update the multimap but will lead * to a revised value being returned by {@code getValue()}. */ @Override public List<Entry<K, V>> entries() { return (List<Entry<K, V>>) super.entries(); } @Override List<Entry<K, V>> createEntries() { return new AbstractSequentialList<Entry<K, V>>() { @Override public int size() { return size; } @Override public ListIterator<Entry<K, V>> listIterator(int index) { return new NodeIterator(index); } }; } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Map<K, Collection<V>> createAsMap() { return new Multimaps.AsMap<K, V>(this); } /** * @serialData the number of distinct keys, and then for each distinct key: * the first key, the number of values for that key, and the key's values, * followed by successive keys and values from the entries() ordering */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(size()); for (Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyToKeyList = Maps.newLinkedHashMap(); int size = stream.readInt(); for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") // reading data stored by writeObject K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject V value = (V) stream.readObject(); put(key, value); } } @GwtIncompatible("java serialization not supported") private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * An immutable {@code SortedMultiset} that stores its elements in a sorted array. Some instances * are ordered by an explicit comparator, while others follow the natural sort ordering of their * elements. Either way, null elements are not supported. * * <p>Unlike {@link Multisets#unmodifiableSortedMultiset}, which is a <i>view</i> of a separate * collection that can still change, an instance of {@code ImmutableSortedMultiset} contains its * own private data and will <i>never</i> change. This class is convenient for {@code public static * final} multisets ("constant multisets") and also lets you easily make a "defensive copy" of a * set provided to your class by a caller. * * <p>The multisets returned by the {@link #headMultiset}, {@link #tailMultiset}, and * {@link #subMultiset} methods share the same array as the original multiset, preventing that * array from being garbage collected. If this is a concern, the data may be copied into a * correctly-sized array by calling {@link #copyOfSorted}. * * <p><b>Note on element equivalence:</b> The {@link #contains(Object)}, * {@link #containsAll(Collection)}, and {@link #equals(Object)} implementations must check whether * a provided object is equivalent to an element in the collection. Unlike most collections, an * {@code ImmutableSortedMultiset} doesn't use {@link Object#equals} to determine if two elements * are equivalent. Instead, with an explicit comparator, the following relation determines whether * elements {@code x} and {@code y} are equivalent: * * <pre> {@code * * {(x, y) | comparator.compare(x, y) == 0}}</pre> * * <p>With natural ordering of elements, the following relation determines whether two elements are * equivalent: * * <pre> {@code * * {(x, y) | x.compareTo(y) == 0}}</pre> * * <b>Warning:</b> Like most multisets, an {@code ImmutableSortedMultiset} will not function * correctly if an element is modified after being placed in the multiset. For this reason, and to * avoid general confusion, it is strongly recommended to place only immutable objects into this * collection. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as it has no public or * protected constructors. Thus, instances of this type are guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Louis Wasserman * @since 12.0 */ @Beta @GwtIncompatible("hasn't been tested yet") public abstract class ImmutableSortedMultiset<E> extends ImmutableSortedMultisetFauxverideShim<E> implements SortedMultiset<E> { // TODO(user): GWT compatibility private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural(); private static final ImmutableSortedMultiset<Comparable> NATURAL_EMPTY_MULTISET = new EmptyImmutableSortedMultiset<Comparable>(NATURAL_ORDER); /** * Returns the empty immutable sorted multiset. */ @SuppressWarnings("unchecked") public static <E> ImmutableSortedMultiset<E> of() { return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; } /** * Returns an immutable sorted multiset containing a single element. */ public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E element) { RegularImmutableSortedSet<E> elementSet = (RegularImmutableSortedSet<E>) ImmutableSortedSet.of(element); int[] counts = {1}; long[] cumulativeCounts = {0, 1}; return new RegularImmutableSortedMultiset<E>(elementSet, counts, cumulativeCounts, 0, 1); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of(E e1, E e2, E e3) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4, E e5) { return copyOf(Ordering.natural(), Arrays.asList(e1, e2, e3, e4, e5)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) { int size = remaining.length + 6; List<E> all = Lists.newArrayListWithCapacity(size); Collections.addAll(all, e1, e2, e3, e4, e5, e6); Collections.addAll(all, remaining); return copyOf(Ordering.natural(), all); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * @throws NullPointerException if any of {@code elements} is null */ public static <E extends Comparable<? super E>> ImmutableSortedMultiset<E> copyOf(E[] elements) { return copyOf(Ordering.natural(), Arrays.asList(elements)); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. To create a copy of a {@code SortedMultiset} that preserves the * comparator, call {@link #copyOfSorted} instead. This method iterates over {@code elements} at * most once. * * <p>Note that if {@code s} is a {@code multiset<String>}, then {@code * ImmutableSortedMultiset.copyOf(s)} returns an {@code ImmutableSortedMultiset<String>} * containing each of the strings in {@code s}, while {@code ImmutableSortedMultiset.of(s)} * returns an {@code ImmutableSortedMultiset<multiset<String>>} containing one element (the given * multiset itself). * * <p>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. * * <p>This method is not type-safe, as it may be called on elements that are not mutually * comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf(Iterable<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedMultisetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted multiset containing the given elements sorted by their natural * ordering. * * <p>This method is not type-safe, as it may be called on elements that are not mutually * comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedMultisetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted multiset containing the given elements sorted by the given {@code * Comparator}. * * @throws NullPointerException if {@code comparator} or any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf( Comparator<? super E> comparator, Iterator<? extends E> elements) { checkNotNull(comparator); return new Builder<E>(comparator).addAll(elements).build(); } /** * Returns an immutable sorted multiset containing the given elements sorted by the given {@code * Comparator}. This method iterates over {@code elements} at most once. * * <p>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. * * @throws NullPointerException if {@code comparator} or any of {@code elements} is null */ public static <E> ImmutableSortedMultiset<E> copyOf( Comparator<? super E> comparator, Iterable<? extends E> elements) { if (elements instanceof ImmutableSortedMultiset) { @SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts ImmutableSortedMultiset<E> multiset = (ImmutableSortedMultiset<E>) elements; if (comparator.equals(multiset.comparator())) { if (multiset.isPartialView()) { return copyOfSortedEntries(comparator, multiset.entrySet().asList()); } else { return multiset; } } } elements = Lists.newArrayList(elements); // defensive copy TreeMultiset<E> sortedCopy = TreeMultiset.create(checkNotNull(comparator)); Iterables.addAll(sortedCopy, elements); return copyOfSortedEntries(comparator, sortedCopy.entrySet()); } /** * Returns an immutable sorted multiset containing the elements of a sorted multiset, sorted by * the same {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which * always uses the natural ordering of the elements. * * <p>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. * * <p>This method is safe to use even when {@code sortedMultiset} is a synchronized or concurrent * collection that is currently being modified by another thread. * * @throws NullPointerException if {@code sortedMultiset} or any of its elements is null */ public static <E> ImmutableSortedMultiset<E> copyOfSorted(SortedMultiset<E> sortedMultiset) { return copyOfSortedEntries(sortedMultiset.comparator(), Lists.newArrayList(sortedMultiset.entrySet())); } private static <E> ImmutableSortedMultiset<E> copyOfSortedEntries( Comparator<? super E> comparator, Collection<Entry<E>> entries) { if (entries.isEmpty()) { return emptyMultiset(comparator); } ImmutableList.Builder<E> elementsBuilder = new ImmutableList.Builder<E>(entries.size()); int[] counts = new int[entries.size()]; long[] cumulativeCounts = new long[entries.size() + 1]; int i = 0; for (Entry<E> entry : entries) { elementsBuilder.add(entry.getElement()); counts[i] = entry.getCount(); cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i]; i++; } return new RegularImmutableSortedMultiset<E>( new RegularImmutableSortedSet<E>(elementsBuilder.build(), comparator), counts, cumulativeCounts, 0, entries.size()); } @SuppressWarnings("unchecked") static <E> ImmutableSortedMultiset<E> emptyMultiset(Comparator<? super E> comparator) { if (NATURAL_ORDER.equals(comparator)) { return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; } return new EmptyImmutableSortedMultiset<E>(comparator); } ImmutableSortedMultiset() {} @Override public final Comparator<? super E> comparator() { return elementSet().comparator(); } @Override public abstract ImmutableSortedSet<E> elementSet(); transient ImmutableSortedMultiset<E> descendingMultiset; @Override public ImmutableSortedMultiset<E> descendingMultiset() { ImmutableSortedMultiset<E> result = descendingMultiset; if (result == null) { return descendingMultiset = new DescendingImmutableSortedMultiset<E>(this); } return result; } /** * {@inheritDoc} * * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final Entry<E> pollFirstEntry() { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * <p>This implementation is guaranteed to throw an {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final Entry<E> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public abstract ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType); @Override public ImmutableSortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { checkArgument(comparator().compare(lowerBound, upperBound) <= 0, "Expected lowerBound <= upperBound but %s > %s", lowerBound, upperBound); return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType); } @Override public abstract ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType); /** * Returns a builder that creates immutable sorted multisets with an explicit comparator. If the * comparator has a more general type than the set being generated, such as creating a {@code * SortedMultiset<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} * constructor instead. * * @throws NullPointerException if {@code comparator} is null */ public static <E> Builder<E> orderedBy(Comparator<E> comparator) { return new Builder<E>(comparator); } /** * Returns a builder that creates immutable sorted multisets whose elements are ordered by the * reverse of their natural ordering. * * <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather than {@code * Comparable<? super E>} as a workaround for javac <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>. */ public static <E extends Comparable<E>> Builder<E> reverseOrder() { return new Builder<E>(Ordering.natural().reverse()); } /** * Returns a builder that creates immutable sorted multisets whose elements are ordered by their * natural ordering. The sorted multisets use {@link Ordering#natural()} as the comparator. This * method provides more type-safety than {@link #builder}, as it can be called only for classes * that implement {@link Comparable}. * * <p>Note: the type parameter {@code E} extends {@code Comparable<E>} rather than {@code * Comparable<? super E>} as a workaround for javac <a * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug 6468354</a>. */ public static <E extends Comparable<E>> Builder<E> naturalOrder() { return new Builder<E>(Ordering.natural()); } /** * A builder for creating immutable multiset instances, especially {@code public static final} * multisets ("constant multisets"). Example: * * <pre> {@code * * public static final ImmutableSortedMultiset<Bean> BEANS = * new ImmutableSortedMultiset.Builder<Bean>() * .addCopies(Bean.COCOA, 4) * .addCopies(Bean.GARDEN, 6) * .addCopies(Bean.RED, 8) * .addCopies(Bean.BLACK_EYED, 10) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build * multiple multisets in series. * * @since 12.0 */ public static class Builder<E> extends ImmutableMultiset.Builder<E> { private final Comparator<? super E> comparator; /** * Creates a new builder. The returned builder is equivalent to the builder generated by * {@link ImmutableSortedMultiset#orderedBy(Comparator)}. */ public Builder(Comparator<? super E> comparator) { super(TreeMultiset.<E>create(comparator)); this.comparator = checkNotNull(comparator); } /** * Adds {@code element} to the {@code ImmutableSortedMultiset}. * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds a number of occurrences of an element to this {@code ImmutableSortedMultiset}. * * @param element the element to add * @param occurrences the number of occurrences of the element to add. May be zero, in which * case no change will be made. * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation * would result in more than {@link Integer#MAX_VALUE} occurrences of the element */ @Override public Builder<E> addCopies(E element, int occurrences) { super.addCopies(element, occurrences); return this; } /** * Adds or removes the necessary occurrences of an element such that the element attains the * desired count. * * @param element the element to add or remove occurrences of * @param count the desired count of the element in this multiset * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null * @throws IllegalArgumentException if {@code count} is negative */ @Override public Builder<E> setCount(E element, int count) { super.setCount(element, count); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the {@code Iterable} to add to the {@code ImmutableSortedMultiset} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. * * @param elements the elements to add to the {@code ImmutableSortedMultiset} * @return this {@code Builder} object * @throws NullPointerException if {@code 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 {@code ImmutableSortedMultiset} based on the contents of the {@code * Builder}. */ @Override public ImmutableSortedMultiset<E> build() { return copyOfSorted((SortedMultiset<E>) contents); } } private static final class SerializedForm implements Serializable { Comparator comparator; Object[] elements; int[] counts; SerializedForm(SortedMultiset<?> multiset) { this.comparator = multiset.comparator(); int n = multiset.entrySet().size(); elements = new Object[n]; counts = new int[n]; int i = 0; for (Entry<?> entry : multiset.entrySet()) { elements[i] = entry.getElement(); counts[i] = entry.getCount(); i++; } } @SuppressWarnings("unchecked") Object readResolve() { int n = elements.length; Builder<Object> builder = orderedBy(comparator); for (int i = 0; i < n; i++) { builder.addCopies(elements[i], counts[i]); } return builder.build(); } } @Override Object writeReplace() { return new SerializedForm(this); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A collection that maps keys to values, similar to {@link Map}, but in which * each key may be associated with <i>multiple</i> values. You can visualize the * contents of a multimap either as a map from keys to <i>nonempty</i> * collections of values: * * <ul> * <li>a → 1, 2 * <li>b → 3 * </ul> * * ... or as a single "flattened" collection of key-value pairs: * * <ul> * <li>a → 1 * <li>a → 2 * <li>b → 3 * </ul> * * <p><b>Important:</b> although the first interpretation resembles how most * multimaps are <i>implemented</i>, the design of the {@code Multimap} API is * based on the <i>second</i> form. So, using the multimap shown above as an * example, the {@link #size} is {@code 3}, not {@code 2}, and the {@link * #values} collection is {@code [1, 2, 3]}, not {@code [[1, 2], [3]]}. For * those times when the first style is more useful, use the multimap's {@link * #asMap} view (or create a {@code Map<K, Collection<V>>} in the first place). * * <h3>Example</h3> * * <p>The following code: <pre> {@code * * ListMultimap<String, String> multimap = ArrayListMultimap.create(); * for (President pres : US_PRESIDENTS_IN_ORDER) { * multimap.put(pres.firstName(), pres.lastName()); * } * for (String firstName : multimap.keySet()) { * List<String> lastNames = multimap.get(firstName); * out.println(firstName + ": " + lastNames); * }}</pre> * * ... produces output such as: <pre> {@code * * Zachary: [Taylor] * John: [Adams, Adams, Tyler, Kennedy] // Remember, Quincy! * George: [Washington, Bush, Bush] * Grover: [Cleveland, Cleveland] // Two, non-consecutive terms, rep'ing NJ! * ...}</pre> * * <h3>Views</h3> * * <p>Much of the power of the multimap API comes from the <i>view * collections</i> it provides. These always reflect the latest state of the * multimap itself. When they support modification, the changes are * <i>write-through</i> (they automatically update the backing multimap). These * view collections are: * * <ul> * <li>{@link #asMap}, mentioned above</li> * <li>{@link #keys}, {@link #keySet}, {@link #values}, {@link #entries}, which * are similar to the corresponding view collections of {@link Map} * <li>and, notably, even the collection returned by {@link #get get(key)} is an * active view of the values corresponding to {@code key} * </ul> * * <p>The collections returned by the {@link #replaceValues replaceValues} and * {@link #removeAll removeAll} methods, which contain values that have just * been removed from the multimap, are naturally <i>not</i> views. * * <h3>Subinterfaces</h3> * * <p>Instead of using the {@code Multimap} interface directly, prefer the * subinterfaces {@link ListMultimap} and {@link SetMultimap}. These take their * names from the fact that the collections they return from {@code get} behave * like (and, of course, implement) {@link List} and {@link Set}, respectively. * * <p>For example, the "presidents" code snippet above used a {@code * ListMultimap}; if it had used a {@code SetMultimap} instead, two presidents * would have vanished, and last names might or might not appear in * chronological order. * * <p><b>Warning:</b> instances of type {@code Multimap} may not implement * {@link Object#equals} in the way you expect (multimaps containing the same * key-value pairs, even in the same order, may or may not be equal). The * recommended subinterfaces provide a much stronger guarantee. * * <h3>Comparison to a map of collections</h3> * * <p>Multimaps are commonly used in places where a {@code Map<K, * Collection<V>>} would otherwise have appeared. The differences include: * * <ul> * <li>There is no need to populate an empty collection before adding an entry * with {@link #put put}. * <li>{@code get} never returns {@code null}, only an empty collection. * <li>A key is contained in the multimap if and only if it maps to at least * one value. Any operation that causes a key to have zero associated * values has the effect of <i>removing</i> that key from the multimap. * <li>The total entry count is available as {@link #size}. * <li>Many complex operations become easier; for example, {@code * Collections.min(multimap.values())} finds the smallest value across all * keys. * </ul> * * <h3>Implementations</h3> * * <p>As always, prefer the immutable implementations, {@link * ImmutableListMultimap} and {@link ImmutableSetMultimap}. General-purpose * mutable implementations are listed above under "All Known Implementing * Classes". You can also create a <i>custom</i> multimap, backed by any {@code * Map} and {@link Collection} types, using the {@link Multimaps#newMultimap * Multimaps.newMultimap} family of methods. Finally, another popular way to * obtain a multimap is using {@link Multimaps#index Multimaps.index}. See * the {@link Multimaps} class for these and other static utilities related * to multimaps. * * <h3>Other Notes</h3> * * <p>All methods that modify the multimap are optional. The view collections * returned by the multimap may or may not be modifiable. Any modification * method that is not supported will throw {@link * UnsupportedOperationException}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap"> * {@code Multimap}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Multimap<K, V> { // Query Operations /** Returns the number of key-value pairs in the multimap. */ int size(); /** Returns {@code true} if the multimap contains no key-value pairs. */ boolean isEmpty(); /** * Returns {@code true} if the multimap contains any values for the specified * key. * * @param key key to search for in multimap */ boolean containsKey(@Nullable Object key); /** * Returns {@code true} if the multimap contains the specified value for any * key. * * @param value value to search for in multimap */ boolean containsValue(@Nullable Object value); /** * Returns {@code true} if the multimap contains the specified key-value pair. * * @param key key to search for in multimap * @param value value to search for in multimap */ boolean containsEntry(@Nullable Object key, @Nullable Object value); // Modification Operations /** * Stores a key-value pair in the multimap. * * <p>Some multimap implementations allow duplicate key-value pairs, in which * case {@code put} always adds a new key-value pair and increases the * multimap size by 1. Other implementations prohibit duplicates, and storing * a key-value pair that's already in the multimap has no effect. * * @param key key to store in the multimap * @param value value to store in the multimap * @return {@code true} if the method increased the size of the multimap, or * {@code false} if the multimap already contained the key-value pair and * doesn't allow duplicates */ boolean put(@Nullable K key, @Nullable V value); /** * Removes a single key-value pair from the multimap. * * @param key key of entry to remove from the multimap * @param value value of entry to remove the multimap * @return {@code true} if the multimap changed */ boolean remove(@Nullable Object key, @Nullable Object value); // Bulk Operations /** * Stores key-value pairs in this multimap with one key and multiple values. * * <p>This is equivalent to <pre> {@code * * for (V value : values) { * put(key, value); * } }</pre> * * <p>In particular, this is a no-op if {@code values} is empty. * * @param key key to store in the multimap * @param values values to store in the multimap * @return {@code true} if the multimap changed */ boolean putAll(@Nullable K key, Iterable<? extends V> values); /** * Copies all of another multimap's key-value pairs into this multimap. The * order in which the mappings are added is determined by * {@code multimap.entries()}. * * @param multimap mappings to store in this multimap * @return {@code true} if the multimap changed */ boolean putAll(Multimap<? extends K, ? extends V> multimap); /** * Stores a collection of values with the same key, replacing any existing * values for that key. * * <p>If {@code values} is empty, this is equivalent to * {@link #removeAll(Object) removeAll(key)}. * * @param key key to store in the multimap * @param values values to store in the multimap * @return the collection of replaced values, or an empty collection if no * values were previously associated with the key. The collection * <i>may</i> be modifiable, but updating it will have no effect on the * multimap. */ Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values); /** * Removes all values associated with a given key. * * <p>Once this method returns, {@code key} will not be mapped to any values, * so it will not appear in {@link #keySet()}, {@link #asMap()}, or any other * views. * * @param key key of entries to remove from the multimap * @return the collection of removed values, or an empty collection if no * values were associated with the provided key. The collection * <i>may</i> be modifiable, but updating it will have no effect on the * multimap. */ Collection<V> removeAll(@Nullable Object key); /** * Removes all key-value pairs from the multimap. */ void clear(); // Views /** * Returns a collection view containing the values associated with {@code key} * in this multimap, if any. Note that even when ({@code containsKey(key)} is * false, {@code get(key)} still returns an empty collection, not {@code * null}. * * <p>Changes to the returned collection will update the underlying multimap, * and vice versa. * * @param key key to search for in multimap * @return a view collection containing the zero or more values that the key * maps to */ Collection<V> get(@Nullable K key); /** * Returns the set of all keys, each appearing once in the returned set. * Changes to the returned set will update the underlying multimap, and vice * versa. * * <p>Note that the key set contains a key if and only if this multimap maps * that key to at least one value. * * @return the collection of distinct keys */ Set<K> keySet(); /** * Returns a collection, which may contain duplicates, of all keys. The number * of times of key appears in the returned multiset equals the number of * mappings the key has in the multimap. Changes to the returned multiset will * update the underlying multimap, and vice versa. * * @return a multiset with keys corresponding to the distinct keys of the * multimap and frequencies corresponding to the number of values that * each key maps to */ Multiset<K> keys(); /** * Returns a collection of all values in the multimap. Changes to the returned * collection will update the underlying multimap, and vice versa. * * @return collection of values, which may include the same value multiple * times if it occurs in multiple mappings */ Collection<V> values(); /** * Returns a collection of all key-value pairs. Changes to the returned * collection will update the underlying multimap, and vice versa. The entries * collection does not support the {@code add} or {@code addAll} operations. * * @return collection of map entries consisting of key-value pairs */ Collection<Map.Entry<K, V>> entries(); /** * Returns a map view that associates each key with the corresponding values * in the multimap. Changes to the returned map, such as element removal, will * update the underlying multimap. The map does not support {@code setValue()} * on its entries, {@code put}, or {@code putAll}. * * <p>When passed a key that is present in the map, {@code * asMap().get(Object)} has the same behavior as {@link #get}, returning a * live collection. When passed a key that is not present, however, {@code * asMap().get(Object)} returns {@code null} instead of an empty collection. * * @return a map view from a key to its collection of values */ Map<K, Collection<V>> asMap(); // Comparison and hashing /** * Compares the specified object with this multimap for equality. Two * multimaps are equal when their map views, as returned by {@link #asMap}, * are also equal. * * <p>In general, two multimaps with identical key-value mappings may or may * not be equal, depending on the implementation. For example, two * {@link SetMultimap} instances with the same key-value mappings are equal, * but equality of two {@link ListMultimap} instances depends on the ordering * of the values for each key. * * <p>A non-empty {@link SetMultimap} cannot be equal to a non-empty * {@link ListMultimap}, since their {@link #asMap} views contain unequal * collections as values. However, any two empty multimaps are equal, because * they both have empty {@link #asMap} views. */ @Override boolean equals(@Nullable Object obj); /** * Returns the hash code for this multimap. * * <p>The hash code of a multimap is defined as the hash code of the map view, * as returned by {@link Multimap#asMap}. */ @Override int hashCode(); }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Multiset.Entry; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; /** * Provides static utility methods for creating and working with {@link * Multiset} instances. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Multisets"> * {@code Multisets}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Multisets { private Multisets() {} /** * Returns an unmodifiable view of the specified multiset. Query operations on * the returned multiset "read through" to the specified multiset, and * attempts to modify the returned multiset result in an * {@link UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is * serializable. * * @param multiset the multiset for which an unmodifiable view is to be * generated * @return an unmodifiable view of the multiset */ public static <E> Multiset<E> unmodifiableMultiset( Multiset<? extends E> multiset) { if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { // Since it's unmodifiable, the covariant cast is safe @SuppressWarnings("unchecked") Multiset<E> result = (Multiset<E>) multiset; return result; } return new UnmodifiableMultiset<E>(checkNotNull(multiset)); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Multiset<E> unmodifiableMultiset( ImmutableMultiset<E> multiset) { return checkNotNull(multiset); } static class UnmodifiableMultiset<E> extends ForwardingMultiset<E> implements Serializable { final Multiset<? extends E> delegate; UnmodifiableMultiset(Multiset<? extends E> delegate) { this.delegate = delegate; } @SuppressWarnings("unchecked") @Override protected Multiset<E> delegate() { // This is safe because all non-covariant methods are overriden return (Multiset<E>) delegate; } transient Set<E> elementSet; Set<E> createElementSet() { return Collections.<E>unmodifiableSet(delegate.elementSet()); } @Override public Set<E> elementSet() { Set<E> es = elementSet; return (es == null) ? elementSet = createElementSet() : es; } transient Set<Multiset.Entry<E>> entrySet; @SuppressWarnings("unchecked") @Override public Set<Multiset.Entry<E>> entrySet() { Set<Multiset.Entry<E>> es = entrySet; return (es == null) // Safe because the returned set is made unmodifiable and Entry // itself is readonly ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet()) : es; } @SuppressWarnings("unchecked") @Override public Iterator<E> iterator() { // Safe because the returned Iterator is made unmodifiable return (Iterator<E>) Iterators.unmodifiableIterator(delegate.iterator()); } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public int add(E element, int occurences) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> elementsToAdd) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object element) { throw new UnsupportedOperationException(); } @Override public int remove(Object element, int occurrences) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> elementsToRemove) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> elementsToRetain) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public int setCount(E element, int count) { throw new UnsupportedOperationException(); } @Override public boolean setCount(E element, int oldCount, int newCount) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified sorted multiset. Query * operations on the returned multiset "read through" to the specified * multiset, and attempts to modify the returned multiset result in an {@link * UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is * serializable. * * @param sortedMultiset the sorted multiset for which an unmodifiable view is * to be generated * @return an unmodifiable view of the multiset * @since 11.0 */ @Beta public static <E> SortedMultiset<E> unmodifiableSortedMultiset( SortedMultiset<E> sortedMultiset) { // it's in its own file so it can be emulated for GWT return new UnmodifiableSortedMultiset<E>(checkNotNull(sortedMultiset)); } /** * Returns an immutable multiset entry with the specified element and count. * The entry will be serializable if {@code e} is. * * @param e the element to be associated with the returned entry * @param n the count to be associated with the returned entry * @throws IllegalArgumentException if {@code n} is negative */ public static <E> Multiset.Entry<E> immutableEntry(@Nullable E e, int n) { return new ImmutableEntry<E>(e, n); } static final class ImmutableEntry<E> extends AbstractEntry<E> implements Serializable { @Nullable final E element; final int count; ImmutableEntry(@Nullable E element, int count) { this.element = element; this.count = count; checkArgument(count >= 0); } @Override @Nullable public E getElement() { return element; } @Override public int getCount() { return count; } private static final long serialVersionUID = 0; } /** * Returns a view of the elements of {@code unfiltered} that satisfy a predicate. The returned * multiset is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting multiset's iterators, and those of its {@code entrySet()} and * {@code elementSet()}, do not support {@code remove()}. However, all other multiset methods * supported by {@code unfiltered} are supported by the returned multiset. When given an element * that doesn't satisfy the predicate, the multiset's {@code add()} and {@code addAll()} methods * throw an {@link IllegalArgumentException}. When methods such as {@code removeAll()} and * {@code clear()} are called on the filtered multiset, only elements that satisfy the filter * will be removed from the underlying multiset. * * <p>The returned multiset isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multiset's methods, such as {@code size()}, iterate across every * element in the underlying multiset and determine which elements satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the returned multiset and use the * copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See * {@link Iterables#filter(Iterable, Class)} for related functionality.) * * @since 14.0 */ @Beta public static <E> Multiset<E> filter(Multiset<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredMultiset) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredMultiset<E> filtered = (FilteredMultiset<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate); return new FilteredMultiset<E>(filtered.unfiltered, combinedPredicate); } return new FilteredMultiset<E>(unfiltered, predicate); } private static final class FilteredMultiset<E> extends AbstractMultiset<E> { final Multiset<E> unfiltered; final Predicate<? super E> predicate; FilteredMultiset(Multiset<E> unfiltered, Predicate<? super E> predicate) { this.unfiltered = checkNotNull(unfiltered); this.predicate = checkNotNull(predicate); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } @Override Set<E> createElementSet() { return Sets.filter(unfiltered.elementSet(), predicate); } @Override Set<Entry<E>> createEntrySet() { return Sets.filter(unfiltered.entrySet(), new Predicate<Entry<E>>() { @Override public boolean apply(Entry<E> entry) { return predicate.apply(entry.getElement()); } }); } @Override Iterator<Entry<E>> entryIterator() { throw new AssertionError("should never be called"); } @Override int distinctElements() { return elementSet().size(); } @Override public int count(@Nullable Object element) { int count = unfiltered.count(element); if (count > 0) { @SuppressWarnings("unchecked") // element is equal to an E E e = (E) element; return predicate.apply(e) ? count : 0; } return 0; } @Override public int add(@Nullable E element, int occurrences) { checkArgument(predicate.apply(element), "Element %s does not match predicate %s", element, predicate); return unfiltered.add(element, occurrences); } @Override public int remove(@Nullable Object element, int occurrences) { Multisets.checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } else { return contains(element) ? unfiltered.remove(element, occurrences) : 0; } } @Override public void clear() { elementSet().clear(); } } /** * Returns the expected number of distinct elements given the specified * elements. The number of distinct elements is only computed if {@code * elements} is an instance of {@code Multiset}; otherwise the default value * of 11 is returned. */ static int inferDistinctElements(Iterable<?> elements) { if (elements instanceof Multiset) { return ((Multiset<?>) elements).elementSet().size(); } return 11; // initial capacity will be rounded up to 16 } /** * Returns an unmodifiable view of the union of two multisets. * In the returned multiset, the count of each element is the <i>maximum</i> * of its counts in the two backing multisets. The iteration order of the * returned multiset matches that of the element set of {@code multiset1} * followed by the members of the element set of {@code multiset2} that are * not contained in {@code multiset1}, with repeated occurrences of the same * element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are * based on different equivalence relations (as {@code HashMultiset} and * {@code TreeMultiset} are). * * @since 14.0 */ @Beta public static <E> Multiset<E> union( final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); return new AbstractMultiset<E>() { @Override public boolean contains(@Nullable Object element) { return multiset1.contains(element) || multiset2.contains(element); } @Override public boolean isEmpty() { return multiset1.isEmpty() && multiset2.isEmpty(); } @Override public int count(Object element) { return Math.max(multiset1.count(element), multiset2.count(element)); } @Override Set<E> createElementSet() { return Sets.union(multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator(); final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator(); // TODO(user): consider making the entries live views return new AbstractIterator<Entry<E>>() { @Override protected Entry<E> computeNext() { if (iterator1.hasNext()) { Entry<? extends E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = Math.max(entry1.getCount(), multiset2.count(element)); return immutableEntry(element, count); } while (iterator2.hasNext()) { Entry<? extends E> entry2 = iterator2.next(); E element = entry2.getElement(); if (!multiset1.contains(element)) { return immutableEntry(element, entry2.getCount()); } } return endOfData(); } }; } @Override int distinctElements() { return elementSet().size(); } }; } /** * Returns an unmodifiable view of the intersection of two multisets. * In the returned multiset, the count of each element is the <i>minimum</i> * of its counts in the two backing multisets, with elements that would have * a count of 0 not included. The iteration order of the returned multiset * matches that of the element set of {@code multiset1}, with repeated * occurrences of the same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are * based on different equivalence relations (as {@code HashMultiset} and * {@code TreeMultiset} are). * * @since 2.0 */ public static <E> Multiset<E> intersection( final Multiset<E> multiset1, final Multiset<?> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); return new AbstractMultiset<E>() { @Override public int count(Object element) { int count1 = multiset1.count(element); return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element)); } @Override Set<E> createElementSet() { return Sets.intersection( multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); // TODO(user): consider making the entries live views return new AbstractIterator<Entry<E>>() { @Override protected Entry<E> computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = Math.min(entry1.getCount(), multiset2.count(element)); if (count > 0) { return immutableEntry(element, count); } } return endOfData(); } }; } @Override int distinctElements() { return elementSet().size(); } }; } /** * Returns an unmodifiable view of the sum of two multisets. * In the returned multiset, the count of each element is the <i>sum</i> of * its counts in the two backing multisets. The iteration order of the * returned multiset matches that of the element set of {@code multiset1} * followed by the members of the element set of {@code multiset2} that * are not contained in {@code multiset1}, with repeated occurrences of the * same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are * based on different equivalence relations (as {@code HashMultiset} and * {@code TreeMultiset} are). * * @since 14.0 */ @Beta public static <E> Multiset<E> sum( final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); // TODO(user): consider making the entries live views return new AbstractMultiset<E>() { @Override public boolean contains(@Nullable Object element) { return multiset1.contains(element) || multiset2.contains(element); } @Override public boolean isEmpty() { return multiset1.isEmpty() && multiset2.isEmpty(); } @Override public int size() { return multiset1.size() + multiset2.size(); } @Override public int count(Object element) { return multiset1.count(element) + multiset2.count(element); } @Override Set<E> createElementSet() { return Sets.union(multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator(); final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator(); return new AbstractIterator<Entry<E>>() { @Override protected Entry<E> computeNext() { if (iterator1.hasNext()) { Entry<? extends E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = entry1.getCount() + multiset2.count(element); return immutableEntry(element, count); } while (iterator2.hasNext()) { Entry<? extends E> entry2 = iterator2.next(); E element = entry2.getElement(); if (!multiset1.contains(element)) { return immutableEntry(element, entry2.getCount()); } } return endOfData(); } }; } @Override int distinctElements() { return elementSet().size(); } }; } /** * Returns an unmodifiable view of the difference of two multisets. * In the returned multiset, the count of each element is the result of the * <i>zero-truncated subtraction</i> of its count in the second multiset from * its count in the first multiset, with elements that would have a count of * 0 not included. The iteration order of the returned multiset matches that * of the element set of {@code multiset1}, with repeated occurrences of the * same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are * based on different equivalence relations (as {@code HashMultiset} and * {@code TreeMultiset} are). * * @since 14.0 */ @Beta public static <E> Multiset<E> difference( final Multiset<E> multiset1, final Multiset<?> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); // TODO(user): consider making the entries live views return new AbstractMultiset<E>() { @Override public int count(@Nullable Object element) { int count1 = multiset1.count(element); return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element)); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); return new AbstractIterator<Entry<E>>() { @Override protected Entry<E> computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = entry1.getCount() - multiset2.count(element); if (count > 0) { return immutableEntry(element, count); } } return endOfData(); } }; } @Override int distinctElements() { return Iterators.size(entryIterator()); } }; } /** * Returns {@code true} if {@code subMultiset.count(o) <= * superMultiset.count(o)} for all {@code o}. * * @since 10.0 */ public static boolean containsOccurrences( Multiset<?> superMultiset, Multiset<?> subMultiset) { checkNotNull(superMultiset); checkNotNull(subMultiset); for (Entry<?> entry : subMultiset.entrySet()) { int superCount = superMultiset.count(entry.getElement()); if (superCount < entry.getCount()) { return false; } } return true; } /** * Modifies {@code multisetToModify} so that its count for an element * {@code e} is at most {@code multisetToRetain.count(e)}. * * <p>To be precise, {@code multisetToModify.count(e)} is set to * {@code Math.min(multisetToModify.count(e), * multisetToRetain.count(e))}. This is similar to * {@link #intersection(Multiset, Multiset) intersection} * {@code (multisetToModify, multisetToRetain)}, but mutates * {@code multisetToModify} instead of returning a view. * * <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps * all occurrences of elements that appear at all in {@code * multisetToRetain}, and deletes all occurrences of all other elements. * * @return {@code true} if {@code multisetToModify} was changed as a result * of this operation * @since 10.0 */ public static boolean retainOccurrences(Multiset<?> multisetToModify, Multiset<?> multisetToRetain) { return retainOccurrencesImpl(multisetToModify, multisetToRetain); } /** * Delegate implementation which cares about the element type. */ private static <E> boolean retainOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRetain); // Avoiding ConcurrentModificationExceptions is tricky. Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int retainCount = occurrencesToRetain.count(entry.getElement()); if (retainCount == 0) { entryIterator.remove(); changed = true; } else if (retainCount < entry.getCount()) { multisetToModify.setCount(entry.getElement(), retainCount); changed = true; } } return changed; } /** * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, * removes one occurrence of {@code e} in {@code multisetToModify}. * * <p>Equivalently, this method modifies {@code multisetToModify} so that * {@code multisetToModify.count(e)} is set to * {@code Math.max(0, multisetToModify.count(e) - * occurrencesToRemove.count(e))}. * * <p>This is <i>not</i> the same as {@code multisetToModify.} * {@link Multiset#removeAll removeAll}{@code (occurrencesToRemove)}, which * removes all occurrences of elements that appear in * {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent * to, albeit more efficient than, the following: <pre> {@code * * for (E e : occurrencesToRemove) { * multisetToModify.remove(e); * }}</pre> * * @return {@code true} if {@code multisetToModify} was changed as a result of * this operation * @since 10.0 */ public static boolean removeOccurrences( Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) { return removeOccurrencesImpl(multisetToModify, occurrencesToRemove); } /** * Delegate that cares about the element types in occurrencesToRemove. */ private static <E> boolean removeOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRemove) { // TODO(user): generalize to removing an Iterable, perhaps checkNotNull(multisetToModify); checkNotNull(occurrencesToRemove); boolean changed = false; Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int removeCount = occurrencesToRemove.count(entry.getElement()); if (removeCount >= entry.getCount()) { entryIterator.remove(); changed = true; } else if (removeCount > 0) { multisetToModify.remove(entry.getElement(), removeCount); changed = true; } } return changed; } /** * Implementation of the {@code equals}, {@code hashCode}, and * {@code toString} methods of {@link Multiset.Entry}. */ abstract static class AbstractEntry<E> implements Multiset.Entry<E> { /** * Indicates whether an object equals this entry, following the behavior * specified in {@link Multiset.Entry#equals}. */ @Override public boolean equals(@Nullable Object object) { if (object instanceof Multiset.Entry) { Multiset.Entry<?> that = (Multiset.Entry<?>) object; return this.getCount() == that.getCount() && Objects.equal(this.getElement(), that.getElement()); } return false; } /** * Return this entry's hash code, following the behavior specified in * {@link Multiset.Entry#hashCode}. */ @Override public int hashCode() { E e = getElement(); return ((e == null) ? 0 : e.hashCode()) ^ getCount(); } /** * Returns a string representation of this multiset entry. The string * representation consists of the associated element if the associated count * is one, and otherwise the associated element followed by the characters * " x " (space, x and space) followed by the count. Elements and counts are * converted to strings as by {@code String.valueOf}. */ @Override public String toString() { String text = String.valueOf(getElement()); int n = getCount(); return (n == 1) ? text : (text + " x " + n); } } /** * An implementation of {@link Multiset#equals}. */ static boolean equalsImpl(Multiset<?> multiset, @Nullable Object object) { if (object == multiset) { return true; } if (object instanceof Multiset) { Multiset<?> that = (Multiset<?>) object; /* * We can't simply check whether the entry sets are equal, since that * approach fails when a TreeMultiset has a comparator that returns 0 * when passed unequal elements. */ if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { return false; } for (Entry<?> entry : that.entrySet()) { if (multiset.count(entry.getElement()) != entry.getCount()) { return false; } } return true; } return false; } /** * An implementation of {@link Multiset#addAll}. */ static <E> boolean addAllImpl( Multiset<E> self, Collection<? extends E> elements) { if (elements.isEmpty()) { return false; } if (elements instanceof Multiset) { Multiset<? extends E> that = cast(elements); for (Entry<? extends E> entry : that.entrySet()) { self.add(entry.getElement(), entry.getCount()); } } else { Iterators.addAll(self, elements.iterator()); } return true; } /** * An implementation of {@link Multiset#removeAll}. */ static boolean removeAllImpl( Multiset<?> self, Collection<?> elementsToRemove) { Collection<?> collection = (elementsToRemove instanceof Multiset) ? ((Multiset<?>) elementsToRemove).elementSet() : elementsToRemove; return self.elementSet().removeAll(collection); } /** * An implementation of {@link Multiset#retainAll}. */ static boolean retainAllImpl( Multiset<?> self, Collection<?> elementsToRetain) { checkNotNull(elementsToRetain); Collection<?> collection = (elementsToRetain instanceof Multiset) ? ((Multiset<?>) elementsToRetain).elementSet() : elementsToRetain; return self.elementSet().retainAll(collection); } /** * An implementation of {@link Multiset#setCount(Object, int)}. */ static <E> int setCountImpl(Multiset<E> self, E element, int count) { checkNonnegative(count, "count"); int oldCount = self.count(element); int delta = count - oldCount; if (delta > 0) { self.add(element, delta); } else if (delta < 0) { self.remove(element, -delta); } return oldCount; } /** * An implementation of {@link Multiset#setCount(Object, int, int)}. */ static <E> boolean setCountImpl( Multiset<E> self, E element, int oldCount, int newCount) { checkNonnegative(oldCount, "oldCount"); checkNonnegative(newCount, "newCount"); if (self.count(element) == oldCount) { self.setCount(element, newCount); return true; } else { return false; } } abstract static class ElementSet<E> extends Sets.ImprovedAbstractSet<E> { abstract Multiset<E> multiset(); @Override public void clear() { multiset().clear(); } @Override public boolean contains(Object o) { return multiset().contains(o); } @Override public boolean containsAll(Collection<?> c) { return multiset().containsAll(c); } @Override public boolean isEmpty() { return multiset().isEmpty(); } @Override public Iterator<E> iterator() { return new TransformedIterator<Entry<E>, E>(multiset().entrySet().iterator()) { @Override E transform(Entry<E> entry) { return entry.getElement(); } }; } @Override public boolean remove(Object o) { int count = multiset().count(o); if (count > 0) { multiset().remove(o, count); return true; } return false; } @Override public int size() { return multiset().entrySet().size(); } } abstract static class EntrySet<E> extends Sets.ImprovedAbstractSet<Entry<E>> { abstract Multiset<E> multiset(); @Override public boolean contains(@Nullable Object o) { if (o instanceof Entry) { /* * The GWT compiler wrongly issues a warning here. */ @SuppressWarnings("cast") Entry<?> entry = (Entry<?>) o; if (entry.getCount() <= 0) { return false; } int count = multiset().count(entry.getElement()); return count == entry.getCount(); } return false; } // GWT compiler warning; see contains(). @SuppressWarnings("cast") @Override public boolean remove(Object object) { if (object instanceof Multiset.Entry) { Entry<?> entry = (Entry<?>) object; Object element = entry.getElement(); int entryCount = entry.getCount(); if (entryCount != 0) { // Safe as long as we never add a new entry, which we won't. @SuppressWarnings("unchecked") Multiset<Object> multiset = (Multiset) multiset(); return multiset.setCount(element, entryCount, 0); } } return false; } @Override public void clear() { multiset().clear(); } } /** * An implementation of {@link Multiset#iterator}. */ static <E> Iterator<E> iteratorImpl(Multiset<E> multiset) { return new MultisetIteratorImpl<E>( multiset, multiset.entrySet().iterator()); } static final class MultisetIteratorImpl<E> implements Iterator<E> { private final Multiset<E> multiset; private final Iterator<Entry<E>> entryIterator; private Entry<E> currentEntry; /** Count of subsequent elements equal to current element */ private int laterCount; /** Count of all elements equal to current element */ private int totalCount; private boolean canRemove; MultisetIteratorImpl( Multiset<E> multiset, Iterator<Entry<E>> entryIterator) { this.multiset = multiset; this.entryIterator = entryIterator; } @Override public boolean hasNext() { return laterCount > 0 || entryIterator.hasNext(); } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } if (laterCount == 0) { currentEntry = entryIterator.next(); totalCount = laterCount = currentEntry.getCount(); } laterCount--; canRemove = true; return currentEntry.getElement(); } @Override public void remove() { Iterators.checkRemove(canRemove); if (totalCount == 1) { entryIterator.remove(); } else { multiset.remove(currentEntry.getElement()); } totalCount--; canRemove = false; } } /** * An implementation of {@link Multiset#size}. */ static int sizeImpl(Multiset<?> multiset) { long size = 0; for (Entry<?> entry : multiset.entrySet()) { size += entry.getCount(); } return Ints.saturatedCast(size); } static void checkNonnegative(int count, String name) { checkArgument(count >= 0, "%s cannot be negative: %s", name, count); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> Multiset<T> cast(Iterable<T> iterable) { return (Multiset<T>) iterable; } private static final Ordering<Entry<?>> DECREASING_COUNT_ORDERING = new Ordering<Entry<?>>() { @Override public int compare(Entry<?> entry1, Entry<?> entry2) { return Ints.compare(entry2.getCount(), entry1.getCount()); } }; /** * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order is * highest count first, with ties broken by the iteration order of the original multiset. * * @since 11.0 */ @Beta public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) { List<Entry<E>> sortedEntries = Multisets.DECREASING_COUNT_ORDERING.immutableSortedCopy(multiset.entrySet()); return ImmutableMultiset.copyFromEntries(sortedEntries); } }
Java
/* * Copyright (C) 2010 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Interface that extends {@code Table} and whose rows are sorted. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * @author Warren Dukes * @since 8.0 */ @GwtCompatible @Beta public interface RowSortedTable<R, C, V> extends Table<R, C, V> { /** * {@inheritDoc} * * <p>This method returns a {@link SortedSet}, instead of the {@code Set} * specified in the {@link Table} interface. */ @Override SortedSet<R> rowKeySet(); /** * {@inheritDoc} * * <p>This method returns a {@link SortedMap}, instead of the {@code Map} * specified in the {@link Table} interface. */ @Override SortedMap<R, Map<C, V>> rowMap(); }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.Map.Entry; /** * An interface for all filtered multimap types. * * @author Louis Wasserman */ @GwtCompatible interface FilteredMultimap<K, V> extends Multimap<K, V> { Multimap<K, V> unfiltered(); Predicate<? super Entry<K, V>> entryPredicate(); }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Predicate; import java.util.List; import javax.annotation.Nullable; /** * Implementation of {@link Multimaps#filterKeys(ListMultimap, Predicate)}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredKeyListMultimap<K, V> extends FilteredKeyMultimap<K, V> implements ListMultimap<K, V> { FilteredKeyListMultimap(ListMultimap<K, V> unfiltered, Predicate<? super K> keyPredicate) { super(unfiltered, keyPredicate); } @Override public ListMultimap<K, V> unfiltered() { return (ListMultimap<K, V>) super.unfiltered(); } @Override public List<V> get(K key) { return (List<V>) super.get(key); } @Override public List<V> removeAll(@Nullable Object key) { return (List<V>) super.removeAll(key); } @Override public List<V> replaceValues(K key, Iterable<? extends V> values) { return (List<V>) super.replaceValues(key, values); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; /** * Multiset implementation backed by a {@link HashMap}. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public final class HashMultiset<E> extends AbstractMapBasedMultiset<E> { /** * Creates a new, empty {@code HashMultiset} using the default initial * capacity. */ public static <E> HashMultiset<E> create() { return new HashMultiset<E>(); } /** * Creates a new, empty {@code HashMultiset} with the specified expected * number of distinct elements. * * @param distinctElements the expected number of distinct elements * @throws IllegalArgumentException if {@code distinctElements} is negative */ public static <E> HashMultiset<E> create(int distinctElements) { return new HashMultiset<E>(distinctElements); } /** * Creates a new {@code HashMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself * a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> HashMultiset<E> create(Iterable<? extends E> elements) { HashMultiset<E> multiset = create(Multisets.inferDistinctElements(elements)); Iterables.addAll(multiset, elements); return multiset; } private HashMultiset() { super(new HashMap<E, Count>()); } private HashMultiset(int distinctElements) { super(Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); } /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap( Maps.<E, Count>newHashMapWithExpectedSize(distinctElements)); Serialization.populateMultiset(this, stream, distinctElements); } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import javax.annotation.Nullable; /** * An implementation of {@link RangeSet} backed by a {@link TreeMap}. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtIncompatible("uses NavigableMap") public class TreeRangeSet<C extends Comparable<?>> extends AbstractRangeSet<C> { @VisibleForTesting final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** * Creates an empty {@code TreeRangeSet} instance. */ public static <C extends Comparable<?>> TreeRangeSet<C> create() { return new TreeRangeSet<C>(new TreeMap<Cut<C>, Range<C>>()); } /** * Returns a {@code TreeRangeSet} initialized with the ranges in the specified range set. */ public static <C extends Comparable<?>> TreeRangeSet<C> create(RangeSet<C> rangeSet) { TreeRangeSet<C> result = create(); result.addAll(rangeSet); return result; } private TreeRangeSet(NavigableMap<Cut<C>, Range<C>> rangesByLowerCut) { this.rangesByLowerBound = rangesByLowerCut; } private transient Set<Range<C>> asRanges; @Override public Set<Range<C>> asRanges() { Set<Range<C>> result = asRanges; return (result == null) ? asRanges = new AsRanges() : result; } final class AsRanges extends ForwardingCollection<Range<C>> implements Set<Range<C>> { @Override protected Collection<Range<C>> delegate() { return rangesByLowerBound.values(); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } @Override public boolean equals(@Nullable Object o) { return Sets.equalsImpl(this, o); } } @Override @Nullable public Range<C> rangeContaining(C value) { checkNotNull(value); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(Cut.belowValue(value)); if (floorEntry != null && floorEntry.getValue().contains(value)) { return floorEntry.getValue(); } else { // TODO(kevinb): revisit this design choice return null; } } @Override public boolean encloses(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return floorEntry != null && floorEntry.getValue().encloses(range); } @Nullable private Range<C> rangeEnclosing(Range<C> range) { checkNotNull(range); Entry<Cut<C>, Range<C>> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); return (floorEntry != null && floorEntry.getValue().encloses(range)) ? floorEntry.getValue() : null; } @Override public Range<C> span() { Entry<Cut<C>, Range<C>> firstEntry = rangesByLowerBound.firstEntry(); Entry<Cut<C>, Range<C>> lastEntry = rangesByLowerBound.lastEntry(); if (firstEntry == null) { throw new NoSuchElementException(); } return Range.create(firstEntry.getValue().lowerBound, lastEntry.getValue().upperBound); } @Override public void add(Range<C> rangeToAdd) { checkNotNull(rangeToAdd); if (rangeToAdd.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToAdd. Cut<C> lbToAdd = rangeToAdd.lowerBound; Cut<C> ubToAdd = rangeToAdd.upperBound; Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(lbToAdd); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) { // { < }, and we will need to coalesce if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) { // { < > } ubToAdd = rangeBelowLB.upperBound; /* * TODO(cpovirk): can we just "return;" here? Or, can we remove this if() entirely? If * not, add tests to demonstrate the problem with each approach */ } lbToAdd = rangeBelowLB.lowerBound; } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(ubToAdd); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) { // { > }, and we need to coalesce ubToAdd = rangeBelowUB.upperBound; } } // Remove ranges which are strictly enclosed. rangesByLowerBound.subMap(lbToAdd, ubToAdd).clear(); replaceRangeWithSameLowerBound(Range.create(lbToAdd, ubToAdd)); } @Override public void remove(Range<C> rangeToRemove) { checkNotNull(rangeToRemove); if (rangeToRemove.isEmpty()) { return; } // We will use { } to illustrate ranges currently in the range set, and < > // to illustrate rangeToRemove. Entry<Cut<C>, Range<C>> entryBelowLB = rangesByLowerBound.lowerEntry(rangeToRemove.lowerBound); if (entryBelowLB != null) { // { < Range<C> rangeBelowLB = entryBelowLB.getValue(); if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) { // { < }, and we will need to subdivide if (rangeToRemove.hasUpperBound() && rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { < > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowLB.upperBound)); } replaceRangeWithSameLowerBound( Range.create(rangeBelowLB.lowerBound, rangeToRemove.lowerBound)); } } Entry<Cut<C>, Range<C>> entryBelowUB = rangesByLowerBound.floorEntry(rangeToRemove.upperBound); if (entryBelowUB != null) { // { > Range<C> rangeBelowUB = entryBelowUB.getValue(); if (rangeToRemove.hasUpperBound() && rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { // { > } replaceRangeWithSameLowerBound( Range.create(rangeToRemove.upperBound, rangeBelowUB.upperBound)); } } rangesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); } private void replaceRangeWithSameLowerBound(Range<C> range) { if (range.isEmpty()) { rangesByLowerBound.remove(range.lowerBound); } else { rangesByLowerBound.put(range.lowerBound, range); } } private transient RangeSet<C> complement; @Override public RangeSet<C> complement() { RangeSet<C> result = complement; return (result == null) ? complement = new Complement() : result; } @VisibleForTesting static final class RangesByUpperBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; /** * upperBoundWindow represents the headMap/subMap/tailMap view of the entire "ranges by upper * bound" map; it's a constraint on the *keys*, and does not affect the values. */ private final Range<Cut<C>> upperBoundWindow; RangesByUpperBound(NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = Range.all(); } private RangesByUpperBound( NavigableMap<Cut<C>, Range<C>> rangesByLowerBound, Range<Cut<C>> upperBoundWindow) { this.rangesByLowerBound = rangesByLowerBound; this.upperBoundWindow = upperBoundWindow; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (window.isConnected(upperBoundWindow)) { return new RangesByUpperBound<C>(rangesByLowerBound, window.intersection(upperBoundWindow)); } else { return ImmutableSortedMap.of(); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public Range<C> get(@Nullable Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCEs Cut<C> cut = (Cut<C>) key; if (!upperBoundWindow.contains(cut)) { return null; } Entry<Cut<C>, Range<C>> candidate = rangesByLowerBound.lowerEntry(cut); if (candidate != null && candidate.getValue().upperBound.equals(cut)) { return candidate.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * We want to start the iteration at the first range where the upper bound is in * upperBoundWindow. */ final Iterator<Range<C>> backingItr; if (!upperBoundWindow.hasLowerBound()) { backingItr = rangesByLowerBound.values().iterator(); } else { Entry<Cut<C>, Range<C>> lowerEntry = rangesByLowerBound.lowerEntry(upperBoundWindow.lowerEndpoint()); if (lowerEntry == null) { backingItr = rangesByLowerBound.values().iterator(); } else if (upperBoundWindow.lowerBound.isLessThan(lowerEntry.getValue().upperBound)) { backingItr = rangesByLowerBound.tailMap(lowerEntry.getKey(), true).values().iterator(); } else { backingItr = rangesByLowerBound.tailMap(upperBoundWindow.lowerEndpoint(), true) .values().iterator(); } } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); if (upperBoundWindow.upperBound.isLessThan(range.upperBound)) { return endOfData(); } else { return Maps.immutableEntry(range.upperBound, range); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { Collection<Range<C>> candidates; if (upperBoundWindow.hasUpperBound()) { candidates = rangesByLowerBound.headMap(upperBoundWindow.upperEndpoint(), false) .descendingMap().values(); } else { candidates = rangesByLowerBound.descendingMap().values(); } final PeekingIterator<Range<C>> backingItr = Iterators.peekingIterator(candidates.iterator()); if (backingItr.hasNext() && upperBoundWindow.upperBound.isLessThan(backingItr.peek().upperBound)) { backingItr.next(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!backingItr.hasNext()) { return endOfData(); } Range<C> range = backingItr.next(); return upperBoundWindow.lowerBound.isLessThan(range.upperBound) ? Maps.immutableEntry(range.upperBound, range) : endOfData(); } }; } @Override public int size() { if (upperBoundWindow.equals(Range.all())) { return rangesByLowerBound.size(); } return Iterators.size(entryIterator()); } @Override public boolean isEmpty() { return upperBoundWindow.equals(Range.all()) ? rangesByLowerBound.isEmpty() : !entryIterator().hasNext(); } } private static final class ComplementRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { private final NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> positiveRangesByUpperBound; /** * complementLowerBoundWindow represents the headMap/subMap/tailMap view of the entire * "complement ranges by lower bound" map; it's a constraint on the *keys*, and does not affect * the values. */ private final Range<Cut<C>> complementLowerBoundWindow; ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound) { this(positiveRangesByLowerBound, Range.<Cut<C>>all()); } private ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound, Range<Cut<C>> window) { this.positiveRangesByLowerBound = positiveRangesByLowerBound; this.positiveRangesByUpperBound = new RangesByUpperBound<C>(positiveRangesByLowerBound); this.complementLowerBoundWindow = window; } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> subWindow) { if (!complementLowerBoundWindow.isConnected(subWindow)) { return ImmutableSortedMap.of(); } else { subWindow = subWindow.intersection(complementLowerBoundWindow); return new ComplementRangesByLowerBound<C>(positiveRangesByLowerBound, subWindow); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { /* * firstComplementRangeLowerBound is the first complement range lower bound inside * complementLowerBoundWindow. Complement range lower bounds are either positive range upper * bounds, or Cut.belowAll(). * * positiveItr starts at the first positive range with lower bound greater than * firstComplementRangeLowerBound. (Positive range lower bounds correspond to complement range * upper bounds.) */ Collection<Range<C>> positiveRanges; if (complementLowerBoundWindow.hasLowerBound()) { positiveRanges = positiveRangesByUpperBound.tailMap( complementLowerBoundWindow.lowerEndpoint(), complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values(); } else { positiveRanges = positiveRangesByUpperBound.values(); } final PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator( positiveRanges.iterator()); final Cut<C> firstComplementRangeLowerBound; if (complementLowerBoundWindow.contains(Cut.<C>belowAll()) && (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.<C>belowAll())) { firstComplementRangeLowerBound = Cut.belowAll(); } else if (positiveItr.hasNext()) { firstComplementRangeLowerBound = positiveItr.next().upperBound; } else { return Iterators.emptyIterator(); } return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeLowerBound = firstComplementRangeLowerBound; @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound) || nextComplementRangeLowerBound == Cut.<C>aboveAll()) { return endOfData(); } Range<C> negativeRange; if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound); nextComplementRangeLowerBound = positiveRange.upperBound; } else { negativeRange = Range.create(nextComplementRangeLowerBound, Cut.<C>aboveAll()); nextComplementRangeLowerBound = Cut.aboveAll(); } return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { Iterator<Range<C>> itr; /* * firstComplementRangeUpperBound is the upper bound of the last complement range with lower * bound inside complementLowerBoundWindow. * * positiveItr starts at the first positive range with upper bound less than * firstComplementRangeUpperBound. (Positive range upper bounds correspond to complement range * lower bounds.) */ Cut<C> startingPoint = complementLowerBoundWindow.hasUpperBound() ? complementLowerBoundWindow.upperEndpoint() : Cut.<C>aboveAll(); boolean inclusive = complementLowerBoundWindow.hasUpperBound() && complementLowerBoundWindow.upperBoundType() == BoundType.CLOSED; final PeekingIterator<Range<C>> positiveItr = Iterators.peekingIterator(positiveRangesByUpperBound.headMap(startingPoint, inclusive) .descendingMap().values().iterator()); Cut<C> cut; if (positiveItr.hasNext()) { cut = (positiveItr.peek().upperBound == Cut.<C>aboveAll()) ? positiveItr.next().lowerBound : positiveRangesByLowerBound.higherKey(positiveItr.peek().upperBound); } else if (!complementLowerBoundWindow.contains(Cut.<C>belowAll()) || positiveRangesByLowerBound.containsKey(Cut.belowAll())) { return Iterators.emptyIterator(); } else { cut = positiveRangesByLowerBound.higherKey(Cut.<C>belowAll()); } final Cut<C> firstComplementRangeUpperBound = Objects.firstNonNull(cut, Cut.<C>aboveAll()); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeUpperBound = firstComplementRangeUpperBound; @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (nextComplementRangeUpperBound == Cut.<C>belowAll()) { return endOfData(); } else if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); Range<C> negativeRange = Range.create(positiveRange.upperBound, nextComplementRangeUpperBound); nextComplementRangeUpperBound = positiveRange.lowerBound; if (complementLowerBoundWindow.lowerBound.isLessThan(negativeRange.lowerBound)) { return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); } } else if (complementLowerBoundWindow.lowerBound.isLessThan(Cut.<C>belowAll())) { Range<C> negativeRange = Range.create(Cut.<C>belowAll(), nextComplementRangeUpperBound); nextComplementRangeUpperBound = Cut.belowAll(); return Maps.immutableEntry(Cut.<C>belowAll(), negativeRange); } return endOfData(); } }; } @Override public int size() { return Iterators.size(entryIterator()); } @Override @Nullable public Range<C> get(Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") Cut<C> cut = (Cut<C>) key; // tailMap respects the current window Entry<Cut<C>, Range<C>> firstEntry = tailMap(cut, true).firstEntry(); if (firstEntry != null && firstEntry.getKey().equals(cut)) { return firstEntry.getValue(); } } catch (ClassCastException e) { return null; } } return null; } @Override public boolean containsKey(Object key) { return get(key) != null; } } private final class Complement extends TreeRangeSet<C> { Complement() { super(new ComplementRangesByLowerBound<C>(TreeRangeSet.this.rangesByLowerBound)); } @Override public void add(Range<C> rangeToAdd) { TreeRangeSet.this.remove(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { TreeRangeSet.this.add(rangeToRemove); } @Override public boolean contains(C value) { return !TreeRangeSet.this.contains(value); } @Override public RangeSet<C> complement() { return TreeRangeSet.this; } } private static final class SubRangeSetRangesByLowerBound<C extends Comparable<?>> extends AbstractNavigableMap<Cut<C>, Range<C>> { /** * lowerBoundWindow is the headMap/subMap/tailMap view; it only restricts the keys, and does not * affect the values. */ private final Range<Cut<C>> lowerBoundWindow; /** * restriction is the subRangeSet view; ranges are truncated to their intersection with * restriction. */ private final Range<C> restriction; private final NavigableMap<Cut<C>, Range<C>> rangesByLowerBound; private final NavigableMap<Cut<C>, Range<C>> rangesByUpperBound; private SubRangeSetRangesByLowerBound(Range<Cut<C>> lowerBoundWindow, Range<C> restriction, NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) { this.lowerBoundWindow = checkNotNull(lowerBoundWindow); this.restriction = checkNotNull(restriction); this.rangesByLowerBound = checkNotNull(rangesByLowerBound); this.rangesByUpperBound = new RangesByUpperBound<C>(rangesByLowerBound); } private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> window) { if (!window.isConnected(lowerBoundWindow)) { return ImmutableSortedMap.of(); } else { return new SubRangeSetRangesByLowerBound<C>( lowerBoundWindow.intersection(window), restriction, rangesByLowerBound); } } @Override public NavigableMap<Cut<C>, Range<C>> subMap( Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) { return subMap(Range.range( fromKey, BoundType.forBoolean(fromInclusive), toKey, BoundType.forBoolean(toInclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) { return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) { return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } @Override public Comparator<? super Cut<C>> comparator() { return Ordering.<Cut<C>>natural(); } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override @Nullable public Range<C> get(@Nullable Object key) { if (key instanceof Cut) { try { @SuppressWarnings("unchecked") // we catch CCE's Cut<C> cut = (Cut<C>) key; if (!lowerBoundWindow.contains(cut) || cut.compareTo(restriction.lowerBound) < 0 || cut.compareTo(restriction.upperBound) >= 0) { return null; } else if (cut.equals(restriction.lowerBound)) { // it might be present, truncated on the left Range<C> candidate = Maps.valueOrNull(rangesByLowerBound.floorEntry(cut)); if (candidate != null && candidate.upperBound.compareTo(restriction.lowerBound) > 0) { return candidate.intersection(restriction); } } else { Range<C> result = rangesByLowerBound.get(cut); if (result != null) { return result.intersection(restriction); } } } catch (ClassCastException e) { return null; } } return null; } @Override Iterator<Entry<Cut<C>, Range<C>>> entryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } final Iterator<Range<C>> completeRangeItr; if (lowerBoundWindow.upperBound.isLessThan(restriction.lowerBound)) { return Iterators.emptyIterator(); } else if (lowerBoundWindow.lowerBound.isLessThan(restriction.lowerBound)) { // starts at the first range with upper bound strictly greater than restriction.lowerBound completeRangeItr = rangesByUpperBound.tailMap(restriction.lowerBound, false).values().iterator(); } else { // starts at the first range with lower bound above lowerBoundWindow.lowerBound completeRangeItr = rangesByLowerBound.tailMap(lowerBoundWindow.lowerBound.endpoint(), lowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values().iterator(); } final Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (upperBoundOnLowerBounds.isLessThan(nextRange.lowerBound)) { return endOfData(); } else { nextRange = nextRange.intersection(restriction); return Maps.immutableEntry(nextRange.lowerBound, nextRange); } } }; } @Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { if (restriction.isEmpty()) { return Iterators.emptyIterator(); } Cut<Cut<C>> upperBoundOnLowerBounds = Ordering.natural() .min(lowerBoundWindow.upperBound, Cut.belowValue(restriction.upperBound)); final Iterator<Range<C>> completeRangeItr = rangesByLowerBound.headMap( upperBoundOnLowerBounds.endpoint(), upperBoundOnLowerBounds.typeAsUpperBound() == BoundType.CLOSED) .descendingMap().values().iterator(); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { @Override protected Entry<Cut<C>, Range<C>> computeNext() { if (!completeRangeItr.hasNext()) { return endOfData(); } Range<C> nextRange = completeRangeItr.next(); if (restriction.lowerBound.compareTo(nextRange.upperBound) >= 0) { return endOfData(); } nextRange = nextRange.intersection(restriction); if (lowerBoundWindow.contains(nextRange.lowerBound)) { return Maps.immutableEntry(nextRange.lowerBound, nextRange); } else { return endOfData(); } } }; } @Override public int size() { return Iterators.size(entryIterator()); } } @Override public RangeSet<C> subRangeSet(Range<C> view) { return view.equals(Range.<C>all()) ? this : new SubRangeSet(view); } private final class SubRangeSet extends TreeRangeSet<C> { private final Range<C> restriction; SubRangeSet(Range<C> restriction) { super(new SubRangeSetRangesByLowerBound<C>( Range.<Cut<C>>all(), restriction, TreeRangeSet.this.rangesByLowerBound)); this.restriction = restriction; } @Override public boolean encloses(Range<C> range) { if (!restriction.isEmpty() && restriction.encloses(range)) { Range<C> enclosing = TreeRangeSet.this.rangeEnclosing(range); return enclosing != null && !enclosing.intersection(restriction).isEmpty(); } return false; } @Override @Nullable public Range<C> rangeContaining(C value) { if (!restriction.contains(value)) { return null; } Range<C> result = TreeRangeSet.this.rangeContaining(value); return (result == null) ? null : result.intersection(restriction); } @Override public void add(Range<C> rangeToAdd) { checkArgument(restriction.encloses(rangeToAdd), "Cannot add range %s to subRangeSet(%s)", rangeToAdd, restriction); super.add(rangeToAdd); } @Override public void remove(Range<C> rangeToRemove) { if (rangeToRemove.isConnected(restriction)) { TreeRangeSet.this.remove(rangeToRemove.intersection(restriction)); } } @Override public boolean contains(C value) { return restriction.contains(value) && TreeRangeSet.this.contains(value); } @Override public void clear() { TreeRangeSet.this.remove(restriction); } @Override public RangeSet<C> subRangeSet(Range<C> view) { if (view.encloses(restriction)) { return this; } else if (view.isConnected(restriction)) { return new SubRangeSet(restriction.intersection(view)); } else { return ImmutableRangeSet.of(); } } } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Map.Entry; import javax.annotation.Nullable; /** * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} * methods of {@code Entry}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractMapEntry<K, V> implements Entry<K, V> { @Override public abstract K getKey(); @Override public abstract V getValue(); @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } @Override public int hashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * Returns a string representation of the form {@code {key}={value}}. */ @Override public String toString() { return getKey() + "=" + getValue(); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * A comparator, with additional methods to support common operations. This is * an "enriched" version of {@code Comparator}, in the same sense that {@link * FluentIterable} is an enriched {@link Iterable}. * * <p>The common ways to get an instance of {@code Ordering} are: * * <ul> * <li>Subclass it and implement {@link #compare} instead of implementing * {@link Comparator} directly * <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link * #from(Comparator)} * <li>Use the natural ordering, {@link Ordering#natural} * </ul> * * <p>Then you can use the <i>chaining</i> methods to get an altered version of * that {@code Ordering}, including: * * <ul> * <li>{@link #reverse} * <li>{@link #compound(Comparator)} * <li>{@link #onResultOf(Function)} * <li>{@link #nullsFirst} / {@link #nullsLast} * </ul> * * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} * is required, or use any of its special operations, such as:</p> * * <ul> * <li>{@link #immutableSortedCopy} * <li>{@link #isOrdered} / {@link #isStrictlyOrdered} * <li>{@link #min} / {@link #max} * </ul> * * <p>Except as noted, the orderings returned by the factory methods of this * class are serializable if and only if the provided instances that back them * are. For example, if {@code ordering} and {@code function} can themselves be * serialized, then {@code ordering.onResultOf(function)} can as well. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/OrderingExplained"> * {@code Ordering}</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class Ordering<T> implements Comparator<T> { // Natural order /** * Returns a serializable ordering that uses the natural order of the values. * The ordering throws a {@link NullPointerException} when passed a null * parameter. * * <p>The type specification is {@code <C extends Comparable>}, instead of * the technically correct {@code <C extends Comparable<? super C>>}, to * support legacy types from before Java 5. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this?? public static <C extends Comparable> Ordering<C> natural() { return (Ordering<C>) NaturalOrdering.INSTANCE; } // Static factories /** * Returns an ordering based on an <i>existing</i> comparator instance. Note * that there's no need to create a <i>new</i> comparator just to pass it in * here; simply subclass {@code Ordering} and implement its {@code compare} * method directly instead. * * @param comparator the comparator that defines the order * @return comparator itself if it is already an {@code Ordering}; otherwise * an ordering that wraps that comparator */ @GwtCompatible(serializable = true) public static <T> Ordering<T> from(Comparator<T> comparator) { return (comparator instanceof Ordering) ? (Ordering<T>) comparator : new ComparatorOrdering<T>(comparator); } /** * Simply returns its argument. * * @deprecated no need to use this */ @GwtCompatible(serializable = true) @Deprecated public static <T> Ordering<T> from(Ordering<T> ordering) { return checkNotNull(ordering); } /** * Returns an ordering that compares objects according to the order in * which they appear in the given list. Only objects present in the list * (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Subsequent changes * to the {@code valuesInOrder} list will have no effect on the returned * comparator. Null values in the list are not supported. * * <p>The returned comparator throws an {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param valuesInOrder the values that the returned comparator will be able * to compare, in the order the comparator should induce * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if {@code valuesInOrder} contains any * duplicate values (according to {@link Object#equals}) */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit(List<T> valuesInOrder) { return new ExplicitOrdering<T>(valuesInOrder); } /** * Returns an ordering that compares objects according to the order in * which they are given to this method. Only objects present in the argument * list (according to {@link Object#equals}) may be compared. This comparator * imposes a "partial ordering" over the type {@code T}. Null values in the * argument list are not supported. * * <p>The returned comparator throws a {@link ClassCastException} when it * receives an input parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are * serializable. * * @param leastValue the value which the returned comparator should consider * the "least" of all values * @param remainingValuesInOrder the rest of the values that the returned * comparator will be able to compare, in the order the comparator should * follow * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if any duplicate values (according to * {@link Object#equals(Object)}) are present among the method arguments */ @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit( T leastValue, T... remainingValuesInOrder) { return explicit(Lists.asList(leastValue, remainingValuesInOrder)); } // Ordering<Object> singletons /** * Returns an ordering which treats all values as equal, indicating "no * ordering." Passing this ordering to any <i>stable</i> sort algorithm * results in no change to the order of elements. Note especially that {@link * #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the * returned instance these are implemented by simply copying the source list. * * <p>Example: <pre> {@code * * Ordering.allEqual().nullsLast().sortedCopy( * asList(t, null, e, s, null, t, null))}</pre> * * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison * order of those three values (which might not even implement {@link * Comparable} at all). * * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with * equals</i> (as defined {@linkplain Comparator here}). Avoid its use in * APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency * is expected. * * <p>The returned comparator is serializable. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") public static Ordering<Object> allEqual() { return AllEqualOrdering.INSTANCE; } /** * Returns an ordering that compares objects by the natural ordering of their * string representations as returned by {@code toString()}. It does not * support null values. * * <p>The comparator is serializable. */ @GwtCompatible(serializable = true) public static Ordering<Object> usingToString() { return UsingToStringOrdering.INSTANCE; } /** * Returns an arbitrary ordering over all objects, for which {@code compare(a, * b) == 0} implies {@code a == b} (identity equality). There is no meaning * whatsoever to the order imposed, but it is constant for the life of the VM. * * <p>Because the ordering is identity-based, it is not "consistent with * {@link Object#equals(Object)}" as defined by {@link Comparator}. Use * caution when building a {@link SortedSet} or {@link SortedMap} from it, as * the resulting collection will not behave exactly according to spec. * * <p>This ordering is not serializable, as its implementation relies on * {@link System#identityHashCode(Object)}, so its behavior cannot be * preserved across serialization. * * @since 2.0 */ public static Ordering<Object> arbitrary() { return ArbitraryOrderingHolder.ARBITRARY_ORDERING; } private static class ArbitraryOrderingHolder { static final Ordering<Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); } @VisibleForTesting static class ArbitraryOrdering extends Ordering<Object> { @SuppressWarnings("deprecation") // TODO(kevinb): ? private Map<Object, Integer> uids = Platform.tryWeakKeys(new MapMaker()).makeComputingMap( new Function<Object, Integer>() { final AtomicInteger counter = new AtomicInteger(0); @Override public Integer apply(Object from) { return counter.getAndIncrement(); } }); @Override public int compare(Object left, Object right) { if (left == right) { return 0; } else if (left == null) { return -1; } else if (right == null) { return 1; } int leftCode = identityHashCode(left); int rightCode = identityHashCode(right); if (leftCode != rightCode) { return leftCode < rightCode ? -1 : 1; } // identityHashCode collision (rare, but not as rare as you'd think) int result = uids.get(left).compareTo(uids.get(right)); if (result == 0) { throw new AssertionError(); // extremely, extremely unlikely. } return result; } @Override public String toString() { return "Ordering.arbitrary()"; } /* * We need to be able to mock identityHashCode() calls for tests, because it * can take 1-10 seconds to find colliding objects. Mocking frameworks that * can do magic to mock static method calls still can't do so for a system * class, so we need the indirection. In production, Hotspot should still * recognize that the call is 1-morphic and should still be willing to * inline it if necessary. */ int identityHashCode(Object object) { return System.identityHashCode(object); } } // Constructor /** * Constructs a new instance of this class (only invokable by the subclass * constructor, typically implicit). */ protected Ordering() {} // Instance-based factories (and any static equivalents) /** * Returns the reverse of this ordering; the {@code Ordering} equivalent to * {@link Collections#reverseOrder(Comparator)}. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().reverse(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> reverse() { return new ReverseOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as less than all other values * and uses {@code this} to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsFirst(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsFirst() { return new NullsFirstOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as greater than all other * values and uses this ordering to compare non-null values. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsLast(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> nullsLast() { return new NullsLastOrdering<S>(this); } /** * Returns a new ordering on {@code F} which orders elements by first applying * a function to them, then comparing those results using {@code this}. For * example, to compare objects by their string forms, in a case-insensitive * manner, use: <pre> {@code * * Ordering.from(String.CASE_INSENSITIVE_ORDER) * .onResultOf(Functions.toStringFunction())}</pre> */ @GwtCompatible(serializable = true) public <F> Ordering<F> onResultOf(Function<F, ? extends T> function) { return new ByFunctionOrdering<F, T>(function, this); } <T2 extends T> Ordering<Map.Entry<T2, ?>> onKeys() { return onResultOf(Maps.<T2>keyFunction()); } /** * Returns an ordering which first uses the ordering {@code this}, but which * in the event of a "tie", then delegates to {@code secondaryComparator}. * For example, to sort a bug list first by status and second by priority, you * might use {@code byStatus.compound(byPriority)}. For a compound ordering * with three or more components, simply chain multiple calls to this method. * * <p>An ordering produced by this method, or a chain of calls to this method, * is equivalent to one created using {@link Ordering#compound(Iterable)} on * the same component comparators. */ @GwtCompatible(serializable = true) public <U extends T> Ordering<U> compound( Comparator<? super U> secondaryComparator) { return new CompoundOrdering<U>(this, checkNotNull(secondaryComparator)); } /** * Returns an ordering which tries each given comparator in order until a * non-zero result is found, returning that result, and returning zero only if * all comparators return zero. The returned ordering is based on the state of * the {@code comparators} iterable at the time it was provided to this * method. * * <p>The returned ordering is equivalent to that produced using {@code * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. * * <p><b>Warning:</b> Supplying an argument with undefined iteration order, * such as a {@link HashSet}, will produce non-deterministic results. * * @param comparators the comparators to try in order */ @GwtCompatible(serializable = true) public static <T> Ordering<T> compound( Iterable<? extends Comparator<? super T>> comparators) { return new CompoundOrdering<T>(comparators); } /** * Returns a new ordering which sorts iterables by comparing corresponding * elements pairwise until a nonzero result is found; imposes "dictionary * order". If the end of one iterable is reached, but not the other, the * shorter iterable is considered to be less than the longer one. For example, * a lexicographical natural ordering over integers considers {@code * [] < [1] < [1, 1] < [1, 2] < [2]}. * * <p>Note that {@code ordering.lexicographical().reverse()} is not * equivalent to {@code ordering.reverse().lexicographical()} (consider how * each would order {@code [1]} and {@code [1, 1]}). * * @since 2.0 */ @GwtCompatible(serializable = true) // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<Iterable<String>> o = // Ordering.<String>natural().lexicographical(); public <S extends T> Ordering<Iterable<S>> lexicographical() { /* * Note that technically the returned ordering should be capable of * handling not just {@code Iterable<S>} instances, but also any {@code * Iterable<? extends S>}. However, the need for this comes up so rarely * that it doesn't justify making everyone else deal with the very ugly * wildcard. */ return new LexicographicalOrdering<S>(this); } // Regular instance methods // Override to add @Nullable @Override public abstract int compare(@Nullable T left, @Nullable T right); /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. The * iterator will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @param iterator the iterator whose minimum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. * * @since 11.0 */ public <E extends T> E min(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E minSoFar = iterator.next(); while (iterator.hasNext()) { minSoFar = min(minSoFar, iterator.next()); } return minSoFar; } /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. * * @param iterable the iterable whose minimum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(Iterable<E> iterable) { return min(iterable.iterator()); } /** * Returns the lesser of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code min} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if less than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min(@Nullable E a, @Nullable E b) { return (compare(a, b) <= 0) ? a : b; } /** * Returns the least of the specified values according to this ordering. If * there are multiple least values, the first of those is returned. * * @param a value to compare, returned if less than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E min( @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { E minSoFar = min(min(a, b), c); for (E r : rest) { minSoFar = min(minSoFar, r); } return minSoFar; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. The * iterator will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @param iterator the iterator whose maximum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. * * @since 11.0 */ public <E extends T> E max(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E maxSoFar = iterator.next(); while (iterator.hasNext()) { maxSoFar = max(maxSoFar, iterator.next()); } return maxSoFar; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. * * @param iterable the iterable whose maximum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(Iterable<E> iterable) { return max(iterable.iterator()); } /** * Returns the greater of the two values according to this ordering. If the * values compare as 0, the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default * implementations of the other {@code max} overloads, so overriding it will * affect their behavior. * * @param a value to compare, returned if greater than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max(@Nullable E a, @Nullable E b) { return (compare(a, b) >= 0) ? a : b; } /** * Returns the greatest of the specified values according to this ordering. If * there are multiple greatest values, the first of those is returned. * * @param a value to compare, returned if greater than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> under this ordering. */ public <E extends T> E max( @Nullable E a, @Nullable E b, @Nullable E c, E... rest) { E maxSoFar = max(max(a, b), c); for (E r : rest) { maxSoFar = max(maxSoFar, r); } return maxSoFar; } /** * Returns the {@code k} least elements of the given iterable according to * this ordering, in order from least to greatest. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} least * elements in ascending order * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { if (iterable instanceof Collection) { Collection<E> collection = (Collection<E>) iterable; if (collection.size() <= 2L * k) { // In this case, just dumping the collection to an array and sorting is // faster than using the implementation for Iterator, which is // specialized for k much smaller than n. @SuppressWarnings("unchecked") // c only contains E's and doesn't escape E[] array = (E[]) collection.toArray(); Arrays.sort(array, this); if (array.length > k) { array = ObjectArrays.arraysCopyOf(array, k); } return Collections.unmodifiableList(Arrays.asList(array)); } } return leastOf(iterable.iterator(), k); } /** * Returns the {@code k} least elements from the given iterator according to * this ordering, in order from least to greatest. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} least * elements in ascending order * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> leastOf(Iterator<E> elements, int k) { checkNotNull(elements); checkArgument(k >= 0, "k (%s) must be nonnegative", k); if (k == 0 || !elements.hasNext()) { return ImmutableList.of(); } else if (k >= Integer.MAX_VALUE / 2) { // k is really large; just do a straightforward sorted-copy-and-sublist ArrayList<E> list = Lists.newArrayList(elements); Collections.sort(list, this); if (list.size() > k) { list.subList(k, list.size()).clear(); } list.trimToSize(); return Collections.unmodifiableList(list); } /* * Our goal is an O(n) algorithm using only one pass and O(k) additional * memory. * * We use the following algorithm: maintain a buffer of size 2*k. Every time * the buffer gets full, find the median and partition around it, keeping * only the lowest k elements. This requires n/k find-median-and-partition * steps, each of which take O(k) time with a traditional quickselect. * * After sorting the output, the whole algorithm is O(n + k log k). It * degrades gracefully for worst-case input (descending order), performs * competitively or wins outright for randomly ordered input, and doesn't * require the whole collection to fit into memory. */ int bufferCap = k * 2; @SuppressWarnings("unchecked") // we'll only put E's in E[] buffer = (E[]) new Object[bufferCap]; E threshold = elements.next(); buffer[0] = threshold; int bufferSize = 1; // threshold is the kth smallest element seen so far. Once bufferSize >= k, // anything larger than threshold can be ignored immediately. while (bufferSize < k && elements.hasNext()) { E e = elements.next(); buffer[bufferSize++] = e; threshold = max(threshold, e); } while (elements.hasNext()) { E e = elements.next(); if (compare(e, threshold) >= 0) { continue; } buffer[bufferSize++] = e; if (bufferSize == bufferCap) { // We apply the quickselect algorithm to partition about the median, // and then ignore the last k elements. int left = 0; int right = bufferCap - 1; int minThresholdPosition = 0; // The leftmost position at which the greatest of the k lower elements // -- the new value of threshold -- might be found. while (left < right) { int pivotIndex = (left + right + 1) >>> 1; int pivotNewIndex = partition(buffer, left, right, pivotIndex); if (pivotNewIndex > k) { right = pivotNewIndex - 1; } else if (pivotNewIndex < k) { left = Math.max(pivotNewIndex, left + 1); minThresholdPosition = pivotNewIndex; } else { break; } } bufferSize = k; threshold = buffer[minThresholdPosition]; for (int i = minThresholdPosition + 1; i < bufferSize; i++) { threshold = max(threshold, buffer[i]); } } } Arrays.sort(buffer, 0, bufferSize, this); bufferSize = Math.min(bufferSize, k); return Collections.unmodifiableList( Arrays.asList(ObjectArrays.arraysCopyOf(buffer, bufferSize))); // We can't use ImmutableList; we have to be null-friendly! } private <E extends T> int partition( E[] values, int left, int right, int pivotIndex) { E pivotValue = values[pivotIndex]; values[pivotIndex] = values[right]; values[right] = pivotValue; int storeIndex = left; for (int i = left; i < right; i++) { if (compare(values[i], pivotValue) < 0) { ObjectArrays.swap(values, storeIndex, i); storeIndex++; } } ObjectArrays.swap(values, right, storeIndex); return storeIndex; } /** * Returns the {@code k} greatest elements of the given iterable according to * this ordering, in order from greatest to least. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest * elements in <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) { // TODO(kevinb): see if delegation is hurting performance noticeably // TODO(kevinb): if we change this implementation, add full unit tests. return reverse().leastOf(iterable, k); } /** * Returns the {@code k} greatest elements from the given iterator according to * this ordering, in order from greatest to least. If there are fewer than * {@code k} elements present, all will be included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting * algorithm; when multiple elements are equivalent, it is undefined which * will come first. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest * elements in <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) { return reverse().leastOf(iterator, k); } /** * Returns a copy of the given iterable sorted by this ordering. The input is * not modified. The returned list is modifiable, serializable, and has random * access. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard * elements that are duplicates according to the comparator. The sort * performed is <i>stable</i>, meaning that such elements will appear in the * resulting list in the same order they appeared in the input. * * @param iterable the elements to be copied and sorted * @return a new list containing the given elements in sorted order */ public <E extends T> List<E> sortedCopy(Iterable<E> iterable) { @SuppressWarnings("unchecked") // does not escape, and contains only E's E[] array = (E[]) Iterables.toArray(iterable); Arrays.sort(array, this); return Lists.newArrayList(Arrays.asList(array)); } /** * Returns an <i>immutable</i> copy of the given iterable sorted by this * ordering. The input is not modified. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard * elements that are duplicates according to the comparator. The sort * performed is <i>stable</i>, meaning that such elements will appear in the * resulting list in the same order they appeared in the input. * * @param iterable the elements to be copied and sorted * @return a new immutable list containing the given elements in sorted order * @throws NullPointerException if {@code iterable} or any of its elements is * null * @since 3.0 */ public <E extends T> ImmutableList<E> immutableSortedCopy( Iterable<E> iterable) { @SuppressWarnings("unchecked") // we'll only ever have E's in here E[] elements = (E[]) Iterables.toArray(iterable); for (E e : elements) { checkNotNull(e); } Arrays.sort(elements, this); return ImmutableList.asImmutableList(elements); } /** * Returns {@code true} if each element in {@code iterable} after the first is * greater than or equal to the element that preceded it, according to this * ordering. Note that this is always true when the iterable has fewer than * two elements. */ public boolean isOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) > 0) { return false; } prev = next; } } return true; } /** * Returns {@code true} if each element in {@code iterable} after the first is * <i>strictly</i> greater than the element that preceded it, according to * this ordering. Note that this is always true when the iterable has fewer * than two elements. */ public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) >= 0) { return false; } prev = next; } } return true; } /** * {@link Collections#binarySearch(List, Object, Comparator) Searches} * {@code sortedList} for {@code key} using the binary search algorithm. The * list must be sorted using this ordering. * * @param sortedList the list to be searched * @param key the key to be searched for */ public int binarySearch(List<? extends T> sortedList, @Nullable T key) { return Collections.binarySearch(sortedList, key, this); } /** * Exception thrown by a {@link Ordering#explicit(List)} or {@link * Ordering#explicit(Object, Object[])} comparator when comparing a value * outside the set of values it can compare. Extending {@link * ClassCastException} may seem odd, but it is required. */ // TODO(kevinb): make this public, document it right @VisibleForTesting static class IncomparableValueException extends ClassCastException { final Object value; IncomparableValueException(Object value) { super("Cannot compare value: " + value); this.value = value; } private static final long serialVersionUID = 0; } // Never make these public static final int LEFT_IS_GREATER = 1; static final int RIGHT_IS_GREATER = -1; }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.EnumMap; import java.util.Map; /** * A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values * are not permitted. An {@code EnumBiMap} and its inverse are both * serializable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap"> * {@code BiMap}</a>. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends AbstractBiMap<K, V> { private transient Class<K> keyType; private transient Class<V> valueType; /** * Returns a new, empty {@code EnumBiMap} using the specified key and value * types. * * @param keyType the key type * @param valueType the value type */ public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Class<K> keyType, Class<V> valueType) { return new EnumBiMap<K, V>(keyType, valueType); } /** * Returns a new bimap with the same mappings as the specified map. If the * specified map is an {@code EnumBiMap}, the new bimap has the same types as * the provided map. Otherwise, the specified map must contain at least one * mapping, in order to determine the key and value types. * * @param map the map whose mappings are to be placed in this map * @throws IllegalArgumentException if map is not an {@code EnumBiMap} * instance and contains no mappings */ public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Map<K, V> map) { EnumBiMap<K, V> bimap = create(inferKeyType(map), inferValueType(map)); bimap.putAll(map); return bimap; } private EnumBiMap(Class<K> keyType, Class<V> valueType) { super(WellBehavedMap.wrap(new EnumMap<K, V>(keyType)), WellBehavedMap.wrap(new EnumMap<V, K>(valueType))); this.keyType = keyType; this.valueType = valueType; } static <K extends Enum<K>> Class<K> inferKeyType(Map<K, ?> map) { if (map instanceof EnumBiMap) { return ((EnumBiMap<K, ?>) map).keyType(); } if (map instanceof EnumHashBiMap) { return ((EnumHashBiMap<K, ?>) map).keyType(); } checkArgument(!map.isEmpty()); return map.keySet().iterator().next().getDeclaringClass(); } private static <V extends Enum<V>> Class<V> inferValueType(Map<?, V> map) { if (map instanceof EnumBiMap) { return ((EnumBiMap<?, V>) map).valueType; } checkArgument(!map.isEmpty()); return map.values().iterator().next().getDeclaringClass(); } /** Returns the associated key type. */ public Class<K> keyType() { return keyType; } /** Returns the associated value type. */ public Class<V> valueType() { return valueType; } @Override K checkKey(K key) { return checkNotNull(key); } @Override V checkValue(V value) { return checkNotNull(value); } /** * @serialData the key class, value class, number of entries, first key, first * value, second key, second value, and so on. */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(keyType); stream.writeObject(valueType); Serialization.writeMap(this, stream); } @SuppressWarnings("unchecked") // reading fields populated by writeObject @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyType = (Class<K>) stream.readObject(); valueType = (Class<V>) stream.readObject(); setDelegates( WellBehavedMap.wrap(new EnumMap<K, V>(keyType)), WellBehavedMap.wrap(new EnumMap<V, K>(valueType))); Serialization.populateMap(this, stream); } @GwtIncompatible("not needed in emulated source.") private static final long serialVersionUID = 0; }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Supplier; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; /** * Implementation of {@code Table} whose iteration ordering across row keys is * sorted by their natural ordering or by a supplied comparator. Note that * iterations across the columns keys for a single row key may or may not be * ordered, depending on the implementation. When rows and columns are both * sorted, it's easier to use the {@link TreeBasedTable} subclass. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * <p>Null keys and values are not supported. * * <p>See the {@link StandardTable} superclass for more information about the * behavior of this class. * * @author Jared Levy */ @GwtCompatible class StandardRowSortedTable<R, C, V> extends StandardTable<R, C, V> implements RowSortedTable<R, C, V> { /* * TODO(jlevy): Consider adding headTable, tailTable, and subTable methods, * which return a Table view with rows keys in a given range. Create a * RowSortedTable subinterface with the revised methods? */ StandardRowSortedTable(SortedMap<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { super(backingMap, factory); } private SortedMap<R, Map<C, V>> sortedBackingMap() { return (SortedMap<R, Map<C, V>>) backingMap; } /** * {@inheritDoc} * * <p>This method returns a {@link SortedSet}, instead of the {@code Set} * specified in the {@link Table} interface. */ @Override public SortedSet<R> rowKeySet() { return (SortedSet<R>) rowMap().keySet(); } /** * {@inheritDoc} * * <p>This method returns a {@link SortedMap}, instead of the {@code Map} * specified in the {@link Table} interface. */ @Override public SortedMap<R, Map<C, V>> rowMap() { return (SortedMap<R, Map<C, V>>) super.rowMap(); } @Override SortedMap<R, Map<C, V>> createRowMap() { return new RowSortedMap(); } private class RowSortedMap extends RowMap implements SortedMap<R, Map<C, V>> { @Override public SortedSet<R> keySet() { return (SortedSet<R>) super.keySet(); } @Override SortedSet<R> createKeySet() { return new Maps.SortedKeySet<R, Map<C, V>>(this); } @Override public Comparator<? super R> comparator() { return sortedBackingMap().comparator(); } @Override public R firstKey() { return sortedBackingMap().firstKey(); } @Override public R lastKey() { return sortedBackingMap().lastKey(); } @Override public SortedMap<R, Map<C, V>> headMap(R toKey) { checkNotNull(toKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().headMap(toKey), factory).rowMap(); } @Override public SortedMap<R, Map<C, V>> subMap(R fromKey, R toKey) { checkNotNull(fromKey); checkNotNull(toKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().subMap(fromKey, toKey), factory).rowMap(); } @Override public SortedMap<R, Map<C, V>> tailMap(R fromKey) { checkNotNull(fromKey); return new StandardRowSortedTable<R, C, V>( sortedBackingMap().tailMap(fromKey), factory).rowMap(); } } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2013 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; /** * Implementation for {@link FilteredMultimap#values()}. * * @author Louis Wasserman */ @GwtCompatible final class FilteredMultimapValues<K, V> extends AbstractCollection<V> { private final FilteredMultimap<K, V> multimap; FilteredMultimapValues(FilteredMultimap<K, V> multimap) { this.multimap = checkNotNull(multimap); } @Override public Iterator<V> iterator() { return Maps.valueIterator(multimap.entries().iterator()); } @Override public boolean contains(@Nullable Object o) { return multimap.containsValue(o); } @Override public int size() { return multimap.size(); } @Override public boolean remove(@Nullable Object o) { Predicate<? super Entry<K, V>> entryPredicate = multimap.entryPredicate(); for (Iterator<Entry<K, V>> unfilteredItr = multimap.unfiltered().entries().iterator(); unfilteredItr.hasNext();) { Map.Entry<K, V> entry = unfilteredItr.next(); if (entryPredicate.apply(entry) && Objects.equal(entry.getValue(), o)) { unfilteredItr.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { return Iterables.removeIf(multimap.unfiltered().entries(), // explicit <Entry<K, V>> is required to build with JDK6 Predicates.<Entry<K, V>>and(multimap.entryPredicate(), Maps.<V>valuePredicateOnEntries(Predicates.in(c)))); } @Override public boolean retainAll(Collection<?> c) { return Iterables.removeIf(multimap.unfiltered().entries(), // explicit <Entry<K, V>> is required to build with JDK6 Predicates.<Entry<K, V>>and(multimap.entryPredicate(), Maps.<V>valuePredicateOnEntries(Predicates.not(Predicates.in(c))))); } @Override public void clear() { multimap.clear(); } }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.concurrent.Immutable; /** * A {@code RegularImmutableTable} optimized for sparse data. */ @GwtCompatible @Immutable final class SparseImmutableTable<R, C, V> extends RegularImmutableTable<R, C, V> { private final ImmutableMap<R, Map<C, V>> rowMap; private final ImmutableMap<C, Map<R, V>> columnMap; private final int[] iterationOrderRow; private final int[] iterationOrderColumn; SparseImmutableTable(ImmutableList<Cell<R, C, V>> cellList, ImmutableSet<R> rowSpace, ImmutableSet<C> columnSpace) { Map<R, Integer> rowIndex = Maps.newHashMap(); Map<R, Map<C, V>> rows = Maps.newLinkedHashMap(); for (R row : rowSpace) { rowIndex.put(row, rows.size()); rows.put(row, new LinkedHashMap<C, V>()); } Map<C, Map<R, V>> columns = Maps.newLinkedHashMap(); for (C col : columnSpace) { columns.put(col, new LinkedHashMap<R, V>()); } int[] iterationOrderRow = new int[cellList.size()]; int[] iterationOrderColumn = new int[cellList.size()]; for (int i = 0; i < cellList.size(); i++) { Cell<R, C, V> cell = cellList.get(i); R rowKey = cell.getRowKey(); C columnKey = cell.getColumnKey(); V value = cell.getValue(); iterationOrderRow[i] = rowIndex.get(rowKey); Map<C, V> thisRow = rows.get(rowKey); iterationOrderColumn[i] = thisRow.size(); V oldValue = thisRow.put(columnKey, value); if (oldValue != null) { throw new IllegalArgumentException("Duplicate value for row=" + rowKey + ", column=" + columnKey + ": " + value + ", " + oldValue); } columns.get(columnKey).put(rowKey, value); } this.iterationOrderRow = iterationOrderRow; this.iterationOrderColumn = iterationOrderColumn; ImmutableMap.Builder<R, Map<C, V>> rowBuilder = ImmutableMap.builder(); for (Map.Entry<R, Map<C, V>> row : rows.entrySet()) { rowBuilder.put(row.getKey(), ImmutableMap.copyOf(row.getValue())); } this.rowMap = rowBuilder.build(); ImmutableMap.Builder<C, Map<R, V>> columnBuilder = ImmutableMap.builder(); for (Map.Entry<C, Map<R, V>> col : columns.entrySet()) { columnBuilder.put(col.getKey(), ImmutableMap.copyOf(col.getValue())); } this.columnMap = columnBuilder.build(); } @Override public ImmutableMap<C, Map<R, V>> columnMap() { return columnMap; } @Override public ImmutableMap<R, Map<C, V>> rowMap() { return rowMap; } @Override public int size() { return iterationOrderRow.length; } @Override Cell<R, C, V> getCell(int index) { int rowIndex = iterationOrderRow[index]; Map.Entry<R, Map<C, V>> rowEntry = rowMap.entrySet().asList().get(rowIndex); ImmutableMap<C, V> row = (ImmutableMap<C, V>) rowEntry.getValue(); int columnIndex = iterationOrderColumn[index]; Map.Entry<C, V> colEntry = row.entrySet().asList().get(columnIndex); return cellOf(rowEntry.getKey(), colEntry.getKey(), colEntry.getValue()); } @Override V getValue(int index) { int rowIndex = iterationOrderRow[index]; ImmutableMap<C, V> row = (ImmutableMap<C, V>) rowMap.values().asList().get(rowIndex); int columnIndex = iterationOrderColumn[index]; return row.values().asList().get(columnIndex); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Collection; import java.util.Iterator; import javax.annotation.Nullable; /** * A collection which forwards all its method calls to another collection. * Subclasses should override one or more methods to modify the behavior of the * backing collection as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingCollection} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #addAll}, which can lead to unexpected behavior. In this case, you should * override {@code addAll} as well, either providing your own implementation, or * delegating to the provided {@code standardAddAll} method. * * <p>The {@code standard} methods are not guaranteed to be thread-safe, even * when all of the methods that they depend on are thread-safe. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingCollection<E> extends ForwardingObject implements Collection<E> { // TODO(user): identify places where thread safety is actually lost /** Constructor for use by subclasses. */ protected ForwardingCollection() {} @Override protected abstract Collection<E> delegate(); @Override public Iterator<E> iterator() { return delegate().iterator(); } @Override public int size() { return delegate().size(); } @Override public boolean removeAll(Collection<?> collection) { return delegate().removeAll(collection); } @Override public boolean isEmpty() { return delegate().isEmpty(); } @Override public boolean contains(Object object) { return delegate().contains(object); } @Override public boolean add(E element) { return delegate().add(element); } @Override public boolean remove(Object object) { return delegate().remove(object); } @Override public boolean containsAll(Collection<?> collection) { return delegate().containsAll(collection); } @Override public boolean addAll(Collection<? extends E> collection) { return delegate().addAll(collection); } @Override public boolean retainAll(Collection<?> collection) { return delegate().retainAll(collection); } @Override public void clear() { delegate().clear(); } @Override public Object[] toArray() { return delegate().toArray(); } @Override public <T> T[] toArray(T[] array) { return delegate().toArray(array); } /** * A sensible definition of {@link #contains} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link * #contains} to forward to this implementation. * * @since 7.0 */ protected boolean standardContains(@Nullable Object object) { return Iterators.contains(iterator(), object); } /** * A sensible definition of {@link #containsAll} in terms of {@link #contains} * . If you override {@link #contains}, you may wish to override {@link * #containsAll} to forward to this implementation. * * @since 7.0 */ protected boolean standardContainsAll(Collection<?> collection) { return Collections2.containsAllImpl(this, collection); } /** * A sensible definition of {@link #addAll} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #addAll} to forward * to this implementation. * * @since 7.0 */ protected boolean standardAddAll(Collection<? extends E> collection) { return Iterators.addAll(this, collection.iterator()); } /** * A sensible definition of {@link #remove} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #remove} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRemove(@Nullable Object object) { Iterator<E> iterator = iterator(); while (iterator.hasNext()) { if (Objects.equal(iterator.next(), object)) { iterator.remove(); return true; } } return false; } /** * A sensible definition of {@link #removeAll} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #removeAll} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRemoveAll(Collection<?> collection) { return Iterators.removeAll(iterator(), collection); } /** * A sensible definition of {@link #retainAll} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #retainAll} to forward to this * implementation. * * @since 7.0 */ protected boolean standardRetainAll(Collection<?> collection) { return Iterators.retainAll(iterator(), collection); } /** * A sensible definition of {@link #clear} in terms of {@link #iterator}, * using the iterator's {@code remove} method. If you override {@link * #iterator}, you may wish to override {@link #clear} to forward to this * implementation. * * @since 7.0 */ protected void standardClear() { Iterators.clear(iterator()); } /** * A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. * If you override {@link #isEmpty}, you may wish to override {@link #isEmpty} * to forward to this implementation. Alternately, it may be more efficient to * implement {@code isEmpty} as {@code size() == 0}. * * @since 7.0 */ protected boolean standardIsEmpty() { return !iterator().hasNext(); } /** * A sensible definition of {@link #toString} in terms of {@link #iterator}. * If you override {@link #iterator}, you may wish to override {@link * #toString} to forward to this implementation. * * @since 7.0 */ protected String standardToString() { return Collections2.toStringImpl(this); } /** * A sensible definition of {@link #toArray()} in terms of {@link * #toArray(Object[])}. If you override {@link #toArray(Object[])}, you may * wish to override {@link #toArray} to forward to this implementation. * * @since 7.0 */ protected Object[] standardToArray() { Object[] newArray = new Object[size()]; return toArray(newArray); } /** * A sensible definition of {@link #toArray(Object[])} in terms of {@link * #size} and {@link #iterator}. If you override either of these methods, you * may wish to override {@link #toArray} to forward to this implementation. * * @since 7.0 */ protected <T> T[] standardToArray(T[] array) { return ObjectArrays.toArrayImpl(this, array); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A collection that associates an ordered pair of keys, called a row key and a * column key, with a single value. A table may be sparse, with only a small * fraction of row key / column key pairs possessing a corresponding value. * * <p>The mappings corresponding to a given row key may be viewed as a {@link * Map} whose keys are the columns. The reverse is also available, associating a * column with a row key / value map. Note that, in some implementations, data * access by column key may have fewer supported operations or worse performance * than data access by row key. * * <p>The methods returning collections or maps always return views of the * underlying table. Updating the table can change the contents of those * collections, and updating the collections will change the table. * * <p>All methods that modify the table are optional, and the views returned by * the table may or may not be modifiable. When modification isn't supported, * those methods will throw an {@link UnsupportedOperationException}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @param <R> the type of the table row keys * @param <C> the type of the table column keys * @param <V> the type of the mapped values * @since 7.0 */ @GwtCompatible public interface Table<R, C, V> { // TODO(jlevy): Consider adding methods similar to ConcurrentMap methods. // Accessors /** * Returns {@code true} if the table contains a mapping with the specified * row and column keys. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ boolean contains(@Nullable Object rowKey, @Nullable Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified * row key. * * @param rowKey key of row to search for */ boolean containsRow(@Nullable Object rowKey); /** * Returns {@code true} if the table contains a mapping with the specified * column. * * @param columnKey key of column to search for */ boolean containsColumn(@Nullable Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified * value. * * @param value value to search for */ boolean containsValue(@Nullable Object value); /** * Returns the value corresponding to the given row and column keys, or * {@code null} if no such mapping exists. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ V get(@Nullable Object rowKey, @Nullable Object columnKey); /** Returns {@code true} if the table contains no mappings. */ boolean isEmpty(); /** * Returns the number of row key / column key / value mappings in the table. */ int size(); /** * Compares the specified object with this table for equality. Two tables are * equal when their cell views, as returned by {@link #cellSet}, are equal. */ @Override boolean equals(@Nullable Object obj); /** * Returns the hash code for this table. The hash code of a table is defined * as the hash code of its cell view, as returned by {@link #cellSet}. */ @Override int hashCode(); // Mutators /** Removes all mappings from the table. */ void clear(); /** * Associates the specified value with the specified keys. If the table * already contained a mapping for those keys, the old value is replaced with * the specified value. * * @param rowKey row key that the value should be associated with * @param columnKey column key that the value should be associated with * @param value value to be associated with the specified keys * @return the value previously associated with the keys, or {@code null} if * no mapping existed for the keys */ V put(R rowKey, C columnKey, V value); /** * Copies all mappings from the specified table to this table. The effect is * equivalent to calling {@link #put} with each row key / column key / value * mapping in {@code table}. * * @param table the table to add to this table */ void putAll(Table<? extends R, ? extends C, ? extends V> table); /** * Removes the mapping, if any, associated with the given keys. * * @param rowKey row key of mapping to be removed * @param columnKey column key of mapping to be removed * @return the value previously associated with the keys, or {@code null} if * no such value existed */ V remove(@Nullable Object rowKey, @Nullable Object columnKey); // Views /** * Returns a view of all mappings that have the given row key. For each row * key / column key / value mapping in the table with that row key, the * returned map associates the column key with the value. If no mappings in * the table have the provided row key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice * versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ Map<C, V> row(R rowKey); /** * Returns a view of all mappings that have the given column key. For each row * key / column key / value mapping in the table with that column key, the * returned map associates the row key with the value. If no mappings in the * table have the provided column key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice * versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ Map<R, V> column(C columnKey); /** * Returns a set of all row key / column key / value triplets. Changes to the * returned set will update the underlying table, and vice versa. The cell set * does not support the {@code add} or {@code addAll} methods. * * @return set of table cells consisting of row key / column key / value * triplets */ Set<Cell<R, C, V>> cellSet(); /** * Returns a set of row keys that have one or more values in the table. * Changes to the set will update the underlying table, and vice versa. * * @return set of row keys */ Set<R> rowKeySet(); /** * Returns a set of column keys that have one or more values in the table. * Changes to the set will update the underlying table, and vice versa. * * @return set of column keys */ Set<C> columnKeySet(); /** * Returns a collection of all values, which may contain duplicates. Changes * to the returned collection will update the underlying table, and vice * versa. * * @return collection of values */ Collection<V> values(); /** * Returns a view that associates each row key with the corresponding map from * column keys to values. Changes to the returned map will update this table. * The returned map does not support {@code put()} or {@code putAll()}, or * {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code rowMap().get()} have the same * behavior as those returned by {@link #row}. Those maps may support {@code * setValue()}, {@code put()}, and {@code putAll()}. * * @return a map view from each row key to a secondary map from column keys to * values */ Map<R, Map<C, V>> rowMap(); /** * Returns a view that associates each column key with the corresponding map * from row keys to values. Changes to the returned map will update this * table. The returned map does not support {@code put()} or {@code putAll()}, * or {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code columnMap().get()} have the * same behavior as those returned by {@link #column}. Those maps may support * {@code setValue()}, {@code put()}, and {@code putAll()}. * * @return a map view from each column key to a secondary map from row keys to * values */ Map<C, Map<R, V>> columnMap(); /** * Row key / column key / value triplet corresponding to a mapping in a table. * * @since 7.0 */ interface Cell<R, C, V> { /** * Returns the row key of this cell. */ R getRowKey(); /** * Returns the column key of this cell. */ C getColumnKey(); /** * Returns the value of this cell. */ V getValue(); /** * Compares the specified object with this cell for equality. Two cells are * equal when they have equal row keys, column keys, and values. */ @Override boolean equals(@Nullable Object obj); /** * Returns the hash code of this cell. * * <p>The hash code of a table cell is equal to {@link * Objects#hashCode}{@code (e.getRowKey(), e.getColumnKey(), e.getValue())}. */ @Override int hashCode(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableList<E> { private ForwardingImmutableList() {} }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Preconditions; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableList} with one or more elements. * * @author Kevin Bourrillion */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization class RegularImmutableList<E> extends ImmutableList<E> { private final transient int offset; private final transient int size; private final transient Object[] array; RegularImmutableList(Object[] array, int offset, int size) { this.offset = offset; this.size = size; this.array = array; } RegularImmutableList(Object[] array) { this(array, 0, array.length); } @Override public int size() { return size; } @Override boolean isPartialView() { return size != array.length; } @Override int copyIntoArray(Object[] dst, int dstOff) { System.arraycopy(array, offset, dst, dstOff, size); return dstOff + size; } // The fake cast to E is safe because the creation methods only allow E's @Override @SuppressWarnings("unchecked") public E get(int index) { Preconditions.checkElementIndex(index, size); return (E) array[index + offset]; } @Override public int indexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = 0; i < size; i++) { if (array[offset + i].equals(object)) { return i; } } return -1; } @Override public int lastIndexOf(@Nullable Object object) { if (object == null) { return -1; } for (int i = size - 1; i >= 0; i--) { if (array[offset + i].equals(object)) { return i; } } return -1; } @Override ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) { return new RegularImmutableList<E>( array, offset + fromIndex, toIndex - fromIndex); } @SuppressWarnings("unchecked") @Override public UnmodifiableListIterator<E> listIterator(int index) { // for performance // The fake cast to E is safe because the creation methods only allow E's return (UnmodifiableListIterator<E>) Iterators.forArray(array, offset, size, index); } // TODO(user): benchmark optimizations for equals() and see if they're worthwhile }
Java
/* * Copyright (C) 2011 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 javax.annotation.Nullable; /** * A skeletal implementation of {@code RangeSet}. * * @author Louis Wasserman */ abstract class AbstractRangeSet<C extends Comparable> implements RangeSet<C> { AbstractRangeSet() {} @Override public boolean contains(C value) { return rangeContaining(value) != null; } @Override public abstract Range<C> rangeContaining(C value); @Override public boolean isEmpty() { return asRanges().isEmpty(); } @Override public void add(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void remove(Range<C> range) { throw new UnsupportedOperationException(); } @Override public void clear() { remove(Range.<C>all()); } @Override public boolean enclosesAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { if (!encloses(range)) { return false; } } return true; } @Override public void addAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { add(range); } } @Override public void removeAll(RangeSet<C> other) { for (Range<C> range : other.asRanges()) { remove(range); } } @Override public abstract boolean encloses(Range<C> otherRange); @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } else if (obj instanceof RangeSet) { RangeSet<?> other = (RangeSet<?>) obj; return this.asRanges().equals(other.asRanges()); } return false; } @Override public final int hashCode() { return asRanges().hashCode(); } @Override public final String toString() { return asRanges().toString(); } }
Java
/* * 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.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ObjectArrays.checkElementsNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.SortedSet; import javax.annotation.Nullable; /** * An immutable {@code SortedSet} that stores its elements in a sorted array. * Some instances are ordered by an explicit comparator, while others follow the * natural sort ordering of their elements. Either way, null elements are not * supported. * * <p>Unlike {@link Collections#unmodifiableSortedSet}, which is a <i>view</i> * of a separate collection that can still change, an instance of {@code * ImmutableSortedSet} contains its own private data and will <i>never</i> * change. This class is convenient for {@code public static final} sets * ("constant sets") and also lets you easily make a "defensive copy" of a set * provided to your class by a caller. * * <p>The sets returned by the {@link #headSet}, {@link #tailSet}, and * {@link #subSet} methods share the same array as the original set, preventing * that array from being garbage collected. If this is a concern, the data may * be copied into a correctly-sized array by calling {@link #copyOfSorted}. * * <p><b>Note on element equivalence:</b> The {@link #contains(Object)}, * {@link #containsAll(Collection)}, and {@link #equals(Object)} * implementations must check whether a provided object is equivalent to an * element in the collection. Unlike most collections, an * {@code ImmutableSortedSet} doesn't use {@link Object#equals} to determine if * two elements are equivalent. Instead, with an explicit comparator, the * following relation determines whether elements {@code x} and {@code y} are * equivalent: <pre> {@code * * {(x, y) | comparator.compare(x, y) == 0}}</pre> * * <p>With natural ordering of elements, the following relation determines whether * two elements are equivalent: <pre> {@code * * {(x, y) | x.compareTo(y) == 0}}</pre> * * <b>Warning:</b> Like most sets, an {@code ImmutableSortedSet} will not * function correctly if an element is modified after being placed in the set. * For this reason, and to avoid general confusion, it is strongly recommended * to place only immutable objects into this collection. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this type are * guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @see ImmutableSet * @author Jared Levy * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library; implements {@code NavigableSet} since 12.0) */ // TODO(benyu): benchmark and optimize all creation paths, which are a mess now @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxverideShim<E> implements NavigableSet<E>, SortedIterable<E> { private static final Comparator<Comparable> NATURAL_ORDER = Ordering.natural(); private static final ImmutableSortedSet<Comparable> NATURAL_EMPTY_SET = new EmptyImmutableSortedSet<Comparable>(NATURAL_ORDER); @SuppressWarnings("unchecked") private static <E> ImmutableSortedSet<E> emptySet() { return (ImmutableSortedSet<E>) NATURAL_EMPTY_SET; } static <E> ImmutableSortedSet<E> emptySet( Comparator<? super E> comparator) { if (NATURAL_ORDER.equals(comparator)) { return emptySet(); } else { return new EmptyImmutableSortedSet<E>(comparator); } } /** * Returns the empty immutable sorted set. */ public static <E> ImmutableSortedSet<E> of() { return emptySet(); } /** * Returns an immutable sorted set containing a single element. */ public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E element) { return new RegularImmutableSortedSet<E>( ImmutableList.of(element), Ordering.natural()); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2) { return construct(Ordering.natural(), 2, e1, e2); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3) { return construct(Ordering.natural(), 3, e1, e2, e3); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3, E e4) { return construct(Ordering.natural(), 4, e1, e2, e3, e4); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any element is null */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3, E e4, E e5) { return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ @SuppressWarnings("unchecked") public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) { Comparable[] contents = new Comparable[6 + remaining.length]; contents[0] = e1; contents[1] = e2; contents[2] = e3; contents[3] = e4; contents[4] = e5; contents[5] = e6; System.arraycopy(remaining, 0, contents, 6, remaining.length); return construct(Ordering.natural(), contents.length, (E[]) contents); } // TODO(kevinb): Consider factory methods that reject duplicates /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@link Comparable#compareTo}, only the first one specified is included. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf( E[] elements) { return construct(Ordering.natural(), elements.length, elements.clone()); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@code compareTo()}, only the first one specified is included. To create a * copy of a {@code SortedSet} that preserves the comparator, call {@link * #copyOfSorted} instead. This method iterates over {@code elements} at most * once. * * <p>Note that if {@code s} is a {@code Set<String>}, then {@code * ImmutableSortedSet.copyOf(s)} returns an {@code ImmutableSortedSet<String>} * containing each of the strings in {@code s}, while {@code * ImmutableSortedSet.of(s)} returns an {@code * ImmutableSortedSet<Set<String>>} containing one element (the given set * itself). * * <p>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. * * <p>This method is not type-safe, as it may be called on elements that are * not mutually comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedSet<E> copyOf( Iterable<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedSetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@code compareTo()}, only the first one specified is included. To create a * copy of a {@code SortedSet} that preserves the comparator, call * {@link #copyOfSorted} instead. This method iterates over {@code elements} * at most once. * * <p>Note that if {@code s} is a {@code Set<String>}, then * {@code ImmutableSortedSet.copyOf(s)} returns an * {@code ImmutableSortedSet<String>} containing each of the strings in * {@code s}, while {@code ImmutableSortedSet.of(s)} returns an * {@code ImmutableSortedSet<Set<String>>} containing one element (the given * set itself). * * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} * is an {@code ImmutableSortedSet}, it may be returned instead of a copy. * * <p>This method is not type-safe, as it may be called on elements that are * not mutually comparable. * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSortedSet<E> copyOf( Collection<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedSetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted set containing the given elements sorted by * their natural ordering. When multiple elements are equivalent according to * {@code compareTo()}, only the first one specified is included. * * <p>This method is not type-safe, as it may be called on elements that are * not mutually comparable. * * @throws ClassCastException if the elements are not mutually comparable * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableSortedSet<E> copyOf( Iterator<? extends E> elements) { // Hack around E not being a subtype of Comparable. // Unsafe, see ImmutableSortedSetFauxverideShim. @SuppressWarnings("unchecked") Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural(); return copyOf(naturalOrder, elements); } /** * Returns an immutable sorted set containing the given elements sorted by * the given {@code Comparator}. When multiple elements are equivalent * according to {@code compareTo()}, only the first one specified is * included. * * @throws NullPointerException if {@code comparator} or any of * {@code elements} is null */ public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Iterator<? extends E> elements) { return new Builder<E>(comparator).addAll(elements).build(); } /** * Returns an immutable sorted set containing the given elements sorted by * the given {@code Comparator}. When multiple elements are equivalent * according to {@code compare()}, only the first one specified is * included. This method iterates over {@code elements} at most once. * * <p>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. * * @throws NullPointerException if {@code comparator} or any of {@code * elements} is null */ public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Iterable<? extends E> elements) { checkNotNull(comparator); boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements); if (hasSameComparator && (elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements; if (!original.isPartialView()) { return original; } } @SuppressWarnings("unchecked") // elements only contains E's; it's safe. E[] array = (E[]) Iterables.toArray(elements); return construct(comparator, array.length, array); } /** * Returns an immutable sorted set containing the given elements sorted by * the given {@code Comparator}. When multiple elements are equivalent * according to {@code compareTo()}, only the first one specified is * included. * * <p>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. * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if {@code comparator} or any of * {@code elements} is null * @since 7.0 (source-compatible since 2.0) */ public static <E> ImmutableSortedSet<E> copyOf( Comparator<? super E> comparator, Collection<? extends E> elements) { return copyOf(comparator, (Iterable<? extends E>) elements); } /** * Returns an immutable sorted set containing the elements of a sorted set, * sorted by the same {@code Comparator}. That behavior differs from {@link * #copyOf(Iterable)}, which always uses the natural ordering of the * elements. * * <p>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. * * <p>This method is safe to use even when {@code sortedSet} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if {@code sortedSet} or any of its elements * is null */ public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) { Comparator<? super E> comparator = SortedIterables.comparator(sortedSet); ImmutableList<E> list = ImmutableList.copyOf(sortedSet); if (list.isEmpty()) { return emptySet(comparator); } else { return new RegularImmutableSortedSet<E>(list, comparator); } } /** * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of * {@code contents}. If {@code k} is the size of the returned {@code ImmutableSortedSet}, then * the sorted unique elements are in the first {@code k} positions of {@code contents}, and * {@code contents[i] == null} for {@code k <= i < n}. * * <p>If {@code k == contents.length}, then {@code contents} may no longer be safe for * modification. * * @throws NullPointerException if any of the first {@code n} elements of {@code contents} is * null */ static <E> ImmutableSortedSet<E> construct( Comparator<? super E> comparator, int n, E... contents) { if (n == 0) { return emptySet(comparator); } checkElementsNotNull(contents, n); Arrays.sort(contents, 0, n, comparator); int uniques = 1; for (int i = 1; i < n; i++) { E cur = contents[i]; E prev = contents[uniques - 1]; if (comparator.compare(cur, prev) != 0) { contents[uniques++] = cur; } } Arrays.fill(contents, uniques, n, null); return new RegularImmutableSortedSet<E>( ImmutableList.<E>asImmutableList(contents, uniques), comparator); } /** * Returns a builder that creates immutable sorted sets with an explicit * comparator. If the comparator has a more general type than the set being * generated, such as creating a {@code SortedSet<Integer>} with a * {@code Comparator<Number>}, use the {@link Builder} constructor instead. * * @throws NullPointerException if {@code comparator} is null */ public static <E> Builder<E> orderedBy(Comparator<E> comparator) { return new Builder<E>(comparator); } /** * Returns a builder that creates immutable sorted sets whose elements are * ordered by the reverse of their natural ordering. */ public static <E extends Comparable<?>> Builder<E> reverseOrder() { return new Builder<E>(Ordering.natural().reverse()); } /** * Returns a builder that creates immutable sorted sets whose elements are * ordered by their natural ordering. The sorted sets use {@link * Ordering#natural()} as the comparator. This method provides more * type-safety than {@link #builder}, as it can be called only for classes * that implement {@link Comparable}. */ public static <E extends Comparable<?>> Builder<E> naturalOrder() { return new Builder<E>(Ordering.natural()); } /** * A builder for creating immutable sorted set instances, especially {@code * public static final} sets ("constant sets"), with a given comparator. * Example: <pre> {@code * * public static final ImmutableSortedSet<Number> LUCKY_NUMBERS = * new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR) * .addAll(SINGLE_DIGIT_PRIMES) * .add(42) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple sets in series. Each set is a superset of the set * created before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<E> extends ImmutableSet.Builder<E> { private final Comparator<? super E> comparator; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableSortedSet#orderedBy}. */ public Builder(Comparator<? super E> comparator) { this.comparator = checkNotNull(comparator); } /** * Adds {@code element} to the {@code ImmutableSortedSet}. If the * {@code ImmutableSortedSet} already contains {@code element}, then * {@code add} has no effect. (only the previously added element * is retained). * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add * @return this {@code Builder} object * @throws NullPointerException if {@code elements} contains a null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add to the {@code ImmutableSortedSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} contains a null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, * ignoring duplicate elements (only the first duplicate element is added). * * @param elements the elements to add to the {@code ImmutableSortedSet} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} contains a null element */ @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } /** * Returns a newly-created {@code ImmutableSortedSet} based on the contents * of the {@code Builder} and its comparator. */ @Override public ImmutableSortedSet<E> build() { @SuppressWarnings("unchecked") // we're careful to put only E's in here E[] contentsArray = (E[]) contents; ImmutableSortedSet<E> result = construct(comparator, size, contentsArray); this.size = result.size(); // we eliminated duplicates in-place in contentsArray return result; } } int unsafeCompare(Object a, Object b) { return unsafeCompare(comparator, a, b); } static int unsafeCompare( Comparator<?> comparator, Object a, Object b) { // Pretend the comparator can compare anything. If it turns out it can't // compare a and b, we should get a CCE on the subsequent line. Only methods // that are spec'd to throw CCE should call this. @SuppressWarnings("unchecked") Comparator<Object> unsafeComparator = (Comparator<Object>) comparator; return unsafeComparator.compare(a, b); } final transient Comparator<? super E> comparator; ImmutableSortedSet(Comparator<? super E> comparator) { this.comparator = comparator; } /** * Returns the comparator that orders the elements, which is * {@link Ordering#natural()} when the natural ordering of the * elements is used. Note that its behavior is not consistent with * {@link SortedSet#comparator()}, which returns {@code null} to indicate * natural ordering. */ @Override public Comparator<? super E> comparator() { return comparator; } @Override // needed to unify the iterator() methods in Collection and SortedIterable public abstract UnmodifiableIterator<E> iterator(); /** * {@inheritDoc} * * <p>This method returns a serializable {@code ImmutableSortedSet}. * * <p>The {@link SortedSet#headSet} documentation states that a subset of a * subset throws an {@link IllegalArgumentException} if passed a * {@code toElement} greater than an earlier {@code toElement}. However, this * method doesn't throw an exception in that situation, but instead keeps the * original {@code toElement}. */ @Override public ImmutableSortedSet<E> headSet(E toElement) { return headSet(toElement, false); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) { return headSetImpl(checkNotNull(toElement), inclusive); } /** * {@inheritDoc} * * <p>This method returns a serializable {@code ImmutableSortedSet}. * * <p>The {@link SortedSet#subSet} documentation states that a subset of a * subset throws an {@link IllegalArgumentException} if passed a * {@code fromElement} smaller than an earlier {@code fromElement}. However, * this method doesn't throw an exception in that situation, but instead keeps * the original {@code fromElement}. Similarly, this method keeps the * original {@code toElement}, instead of throwing an exception, if passed a * {@code toElement} greater than an earlier {@code toElement}. */ @Override public ImmutableSortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ImmutableSortedSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { checkNotNull(fromElement); checkNotNull(toElement); checkArgument(comparator.compare(fromElement, toElement) <= 0); return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); } /** * {@inheritDoc} * * <p>This method returns a serializable {@code ImmutableSortedSet}. * * <p>The {@link SortedSet#tailSet} documentation states that a subset of a * subset throws an {@link IllegalArgumentException} if passed a * {@code fromElement} smaller than an earlier {@code fromElement}. However, * this method doesn't throw an exception in that situation, but instead keeps * the original {@code fromElement}. */ @Override public ImmutableSortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) { return tailSetImpl(checkNotNull(fromElement), inclusive); } /* * These methods perform most headSet, subSet, and tailSet logic, besides * parameter validation. */ abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive); abstract ImmutableSortedSet<E> subSetImpl( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive); abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive); /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public E lower(E e) { return Iterators.getNext(headSet(e, false).descendingIterator(), null); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public E floor(E e) { return Iterators.getNext(headSet(e, true).descendingIterator(), null); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public E ceiling(E e) { return Iterables.getFirst(tailSet(e, true), null); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public E higher(E e) { return Iterables.getFirst(tailSet(e, false), null); } @Override public E first() { return iterator().next(); } @Override public E last() { return descendingIterator().next(); } /** * Guaranteed to throw an exception and leave the set unmodified. * * @since 12.0 * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @GwtIncompatible("NavigableSet") @Override public final E pollFirst() { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the set unmodified. * * @since 12.0 * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @GwtIncompatible("NavigableSet") @Override public final E pollLast() { throw new UnsupportedOperationException(); } @GwtIncompatible("NavigableSet") transient ImmutableSortedSet<E> descendingSet; /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public ImmutableSortedSet<E> descendingSet() { // racy single-check idiom ImmutableSortedSet<E> result = descendingSet; if (result == null) { result = descendingSet = createDescendingSet(); result.descendingSet = this; } return result; } @GwtIncompatible("NavigableSet") ImmutableSortedSet<E> createDescendingSet() { return new DescendingImmutableSortedSet<E>(this); } /** * @since 12.0 */ @GwtIncompatible("NavigableSet") @Override public abstract UnmodifiableIterator<E> descendingIterator(); /** * Returns the position of an element within the set, or -1 if not present. */ abstract int indexOf(@Nullable Object target); /* * This class is used to serialize all ImmutableSortedSet instances, * regardless of implementation type. It captures their "logical contents" * only. This is necessary to ensure that the existence of a particular * implementation type is an implementation detail. */ private static class SerializedForm<E> implements Serializable { final Comparator<? super E> comparator; final Object[] elements; public SerializedForm(Comparator<? super E> comparator, Object[] elements) { this.comparator = comparator; this.elements = elements; } @SuppressWarnings("unchecked") Object readResolve() { return new Builder<E>(comparator).add((E[]) elements).build(); } private static final long serialVersionUID = 0; } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } @Override Object writeReplace() { return new SerializedForm<E>(comparator, toArray()); } }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; /** * "Overrides" the {@link ImmutableMap} static methods that lack * {@link ImmutableSortedMap} equivalents with deprecated, exception-throwing * versions. See {@link ImmutableSortedSetFauxverideShim} for details. * * @author Chris Povirk */ @GwtCompatible abstract class ImmutableSortedMapFauxverideShim<K, V> extends ImmutableMap<K, V> { /** * Not supported. Use {@link ImmutableSortedMap#naturalOrder}, which offers * better type-safety, instead. This method exists only to hide * {@link ImmutableMap#builder} from consumers of {@code ImmutableSortedMap}. * * @throws UnsupportedOperationException always * @deprecated Use {@link ImmutableSortedMap#naturalOrder}, which offers * better type-safety. */ @Deprecated public static <K, V> ImmutableSortedMap.Builder<K, V> builder() { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a map that may contain a * non-{@code Comparable} key.</b> Proper calls will resolve to the version in * {@code ImmutableSortedMap}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass a key of type {@code Comparable} to use {@link * ImmutableSortedMap#of(Comparable, Object)}.</b> */ @Deprecated public static <K, V> ImmutableSortedMap<K, V> of(K k1, V v1) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a map that may contain * non-{@code Comparable} keys.</b> Proper calls will resolve to the version * in {@code ImmutableSortedMap}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass keys of type {@code Comparable} to use {@link * ImmutableSortedMap#of(Comparable, Object, Comparable, Object)}.</b> */ @Deprecated public static <K, V> ImmutableSortedMap<K, V> of( K k1, V v1, K k2, V v2) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a map that may contain * non-{@code Comparable} keys.</b> Proper calls to will resolve to the * version in {@code ImmutableSortedMap}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass keys of type {@code Comparable} to use {@link * ImmutableSortedMap#of(Comparable, Object, Comparable, Object, * Comparable, Object)}.</b> */ @Deprecated public static <K, V> ImmutableSortedMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a map that may contain * non-{@code Comparable} keys.</b> Proper calls will resolve to the version * in {@code ImmutableSortedMap}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass keys of type {@code Comparable} to use {@link * ImmutableSortedMap#of(Comparable, Object, Comparable, Object, * Comparable, Object, Comparable, Object)}.</b> */ @Deprecated public static <K, V> ImmutableSortedMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { throw new UnsupportedOperationException(); } /** * Not supported. <b>You are attempting to create a map that may contain * non-{@code Comparable} keys.</b> Proper calls will resolve to the version * in {@code ImmutableSortedMap}, not this dummy version. * * @throws UnsupportedOperationException always * @deprecated <b>Pass keys of type {@code Comparable} to use {@link * ImmutableSortedMap#of(Comparable, Object, Comparable, Object, * Comparable, Object, Comparable, Object, Comparable, Object)}.</b> */ @Deprecated public static <K, V> ImmutableSortedMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { throw new UnsupportedOperationException(); } // No copyOf() fauxveride; see ImmutableSortedSetFauxverideShim. }
Java
/* * 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.checkState; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * A multiset which maintains the ordering of its elements, according to either their natural order * or an explicit {@link Comparator}. In all cases, this implementation uses * {@link Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to * determine equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the * {@link Comparable} class specification. Otherwise, the resulting multiset will violate the * {@link java.util.Collection} contract, which is specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Louis Wasserman * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class TreeMultiset<E> extends AbstractSortedMultiset<E> implements Serializable { /** * Creates a new, empty multiset, sorted according to the elements' natural order. All elements * inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all * such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the * user attempts to add an element to the multiset that violates this constraint (for example, * the user attempts to add a string element to a set whose elements are integers), the * {@code add(Object)} call will throw a {@code ClassCastException}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create() { return new TreeMultiset<E>(Ordering.natural()); } /** * Creates a new, empty multiset, sorted according to the specified comparator. All elements * inserted into the multiset must be <i>mutually comparable</i> by the specified comparator: * {@code comparator.compare(e1, * e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in * the multiset. If the user attempts to add an element to the multiset that violates this * constraint, the {@code add(Object)} call will throw a {@code ClassCastException}. * * @param comparator * the comparator that will be used to sort this multiset. A null value indicates that * the elements' <i>natural ordering</i> should be used. */ @SuppressWarnings("unchecked") public static <E> TreeMultiset<E> create(@Nullable Comparator<? super E> comparator) { return (comparator == null) ? new TreeMultiset<E>((Comparator) Ordering.natural()) : new TreeMultiset<E>(comparator); } /** * Creates an empty multiset containing the given initial elements, sorted according to the * elements' natural order. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) { TreeMultiset<E> multiset = create(); Iterables.addAll(multiset, elements); return multiset; } private final transient Reference<AvlNode<E>> rootReference; private final transient GeneralRange<E> range; private final transient AvlNode<E> header; TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) { super(range.comparator()); this.rootReference = rootReference; this.range = range; this.header = endLink; } TreeMultiset(Comparator<? super E> comparator) { super(comparator); this.range = GeneralRange.all(comparator); this.header = new AvlNode<E>(null, 1); successor(header, header); this.rootReference = new Reference<AvlNode<E>>(); } /** * A function which can be summed across a subtree. */ private enum Aggregate { SIZE { @Override int nodeAggregate(AvlNode<?> node) { return node.elemCount; } @Override long treeAggregate(@Nullable AvlNode<?> root) { return (root == null) ? 0 : root.totalCount; } }, DISTINCT { @Override int nodeAggregate(AvlNode<?> node) { return 1; } @Override long treeAggregate(@Nullable AvlNode<?> root) { return (root == null) ? 0 : root.distinctElements; } }; abstract int nodeAggregate(AvlNode<?> node); abstract long treeAggregate(@Nullable AvlNode<?> root); } private long aggregateForEntries(Aggregate aggr) { AvlNode<E> root = rootReference.get(); long total = aggr.treeAggregate(root); if (range.hasLowerBound()) { total -= aggregateBelowRange(aggr, root); } if (range.hasUpperBound()) { total -= aggregateAboveRange(aggr, root); } return total; } private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode<E> node) { if (node == null) { return 0; } int cmp = comparator().compare(range.getLowerEndpoint(), node.elem); if (cmp < 0) { return aggregateBelowRange(aggr, node.left); } else if (cmp == 0) { switch (range.getLowerBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left); case CLOSED: return aggr.treeAggregate(node.left); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node) + aggregateBelowRange(aggr, node.right); } } private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode<E> node) { if (node == null) { return 0; } int cmp = comparator().compare(range.getUpperEndpoint(), node.elem); if (cmp > 0) { return aggregateAboveRange(aggr, node.right); } else if (cmp == 0) { switch (range.getUpperBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right); case CLOSED: return aggr.treeAggregate(node.right); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node) + aggregateAboveRange(aggr, node.left); } } @Override public int size() { return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE)); } @Override int distinctElements() { return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT)); } @Override public int count(@Nullable Object element) { try { @SuppressWarnings("unchecked") E e = (E) element; AvlNode<E> root = rootReference.get(); if (!range.contains(e) || root == null) { return 0; } return root.count(comparator(), e); } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } } @Override public int add(@Nullable E element, int occurrences) { checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences); if (occurrences == 0) { return count(element); } checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { comparator().compare(element, element); AvlNode<E> newRoot = new AvlNode<E>(element, occurrences); successor(header, newRoot, header); rootReference.checkAndSet(root, newRoot); return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public int remove(@Nullable Object element, int occurrences) { checkArgument(occurrences >= 0, "occurrences must be >= 0 but was %s", occurrences); if (occurrences == 0) { return count(element); } AvlNode<E> root = rootReference.get(); int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot; try { @SuppressWarnings("unchecked") E e = (E) element; if (!range.contains(e) || root == null) { return 0; } newRoot = root.remove(comparator(), e, occurrences, result); } catch (ClassCastException e) { return 0; } catch (NullPointerException e) { return 0; } rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public int setCount(@Nullable E element, int count) { checkArgument(count >= 0); if (!range.contains(element)) { checkArgument(count == 0); return 0; } AvlNode<E> root = rootReference.get(); if (root == null) { if (count > 0) { add(element, count); } return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, count, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @Override public boolean setCount(@Nullable E element, int oldCount, int newCount) { checkArgument(newCount >= 0); checkArgument(oldCount >= 0); checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { if (oldCount == 0) { if (newCount > 0) { add(element, newCount); } return true; } else { return false; } } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result); rootReference.checkAndSet(root, newRoot); return result[0] == oldCount; } private Entry<E> wrapEntry(final AvlNode<E> baseEntry) { return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return baseEntry.getElement(); } @Override public int getCount() { int result = baseEntry.getCount(); if (result == 0) { return count(getElement()); } else { return result; } } }; } /** * Returns the first node in the tree that is in range. */ @Nullable private AvlNode<E> firstNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasLowerBound()) { E endpoint = range.getLowerEndpoint(); node = rootReference.get().ceiling(comparator(), endpoint); if (node == null) { return null; } if (range.getLowerBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.succ; } } else { node = header.succ; } return (node == header || !range.contains(node.getElement())) ? null : node; } @Nullable private AvlNode<E> lastNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasUpperBound()) { E endpoint = range.getUpperEndpoint(); node = rootReference.get().floor(comparator(), endpoint); if (node == null) { return null; } if (range.getUpperBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.pred; } } else { node = header.pred; } return (node == header || !range.contains(node.getElement())) ? null : node; } @Override Iterator<Entry<E>> entryIterator() { return new Iterator<Entry<E>>() { AvlNode<E> current = firstNode(); Entry<E> prevEntry; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooHigh(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } Entry<E> result = wrapEntry(current); prevEntry = result; if (current.succ == header) { current = null; } else { current = current.succ; } return result; } @Override public void remove() { checkState(prevEntry != null); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override Iterator<Entry<E>> descendingEntryIterator() { return new Iterator<Entry<E>>() { AvlNode<E> current = lastNode(); Entry<E> prevEntry = null; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooLow(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } Entry<E> result = wrapEntry(current); prevEntry = result; if (current.pred == header) { current = null; } else { current = current.pred; } return result; } @Override public void remove() { checkState(prevEntry != null); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override public SortedMultiset<E> headMultiset(@Nullable E upperBound, BoundType boundType) { return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.upTo( comparator(), upperBound, boundType)), header); } @Override public SortedMultiset<E> tailMultiset(@Nullable E lowerBound, BoundType boundType) { return new TreeMultiset<E>(rootReference, range.intersect(GeneralRange.downTo( comparator(), lowerBound, boundType)), header); } static int distinctElements(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.distinctElements; } private static final class Reference<T> { @Nullable private T value; @Nullable public T get() { return value; } public void checkAndSet(@Nullable T expected, T newValue) { if (value != expected) { throw new ConcurrentModificationException(); } value = newValue; } } private static final class AvlNode<E> extends Multisets.AbstractEntry<E> { @Nullable private final E elem; // elemCount is 0 iff this node has been deleted. private int elemCount; private int distinctElements; private long totalCount; private int height; private AvlNode<E> left; private AvlNode<E> right; private AvlNode<E> pred; private AvlNode<E> succ; AvlNode(@Nullable E elem, int elemCount) { checkArgument(elemCount > 0); this.elem = elem; this.elemCount = elemCount; this.totalCount = elemCount; this.distinctElements = 1; this.height = 1; this.left = null; this.right = null; } public int count(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp < 0) { return (left == null) ? 0 : left.count(comparator, e); } else if (cmp > 0) { return (right == null) ? 0 : right.count(comparator, e); } else { return elemCount; } } private AvlNode<E> addRightChild(E e, int count) { right = new AvlNode<E>(e, count); successor(this, right, succ); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } private AvlNode<E> addLeftChild(E e, int count) { left = new AvlNode<E>(e, count); successor(pred, left, this); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } AvlNode<E> add(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { /* * It speeds things up considerably to unconditionally add count to totalCount here, * but that destroys failure atomicity in the case of count overflow. =( */ int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return addLeftChild(e, count); } int initHeight = initLeft.height; left = initLeft.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (left.height == initHeight) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return addRightChild(e, count); } int initHeight = initRight.height; right = initRight.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (right.height == initHeight) ? this : rebalance(); } // adding count to me! No rebalance possible. result[0] = elemCount; long resultCount = (long) elemCount + count; checkArgument(resultCount <= Integer.MAX_VALUE); this.elemCount += count; this.totalCount += count; return this; } AvlNode<E> remove(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return this; } left = initLeft.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return (result[0] == 0) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return this; } right = initRight.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return rebalance(); } // removing count from me! result[0] = elemCount; if (count >= elemCount) { return deleteMe(); } else { this.elemCount -= count; this.totalCount -= count; return this; } } AvlNode<E> setCount(Comparator<? super E> comparator, @Nullable E e, int count, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return (count > 0) ? addLeftChild(e, count) : this; } left = initLeft.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return (count > 0) ? addRightChild(e, count) : this; } right = initRight.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } // setting my count result[0] = elemCount; if (count == 0) { return deleteMe(); } this.totalCount += count - elemCount; this.elemCount = count; return this; } AvlNode<E> setCount( Comparator<? super E> comparator, @Nullable E e, int expectedCount, int newCount, int[] result) { int cmp = comparator.compare(e, elem); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addLeftChild(e, newCount); } return this; } left = initLeft.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addRightChild(e, newCount); } return this; } right = initRight.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } // setting my count result[0] = elemCount; if (expectedCount == elemCount) { if (newCount == 0) { return deleteMe(); } this.totalCount += newCount - elemCount; this.elemCount = newCount; } return this; } private AvlNode<E> deleteMe() { int oldElemCount = this.elemCount; this.elemCount = 0; successor(pred, succ); if (left == null) { return right; } else if (right == null) { return left; } else if (left.height >= right.height) { AvlNode<E> newTop = pred; // newTop is the maximum node in my left subtree newTop.left = left.removeMax(newTop); newTop.right = right; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } else { AvlNode<E> newTop = succ; newTop.right = right.removeMin(newTop); newTop.left = left; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } } // Removes the minimum node from this subtree to be reused elsewhere private AvlNode<E> removeMin(AvlNode<E> node) { if (left == null) { return right; } else { left = left.removeMin(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } // Removes the maximum node from this subtree to be reused elsewhere private AvlNode<E> removeMax(AvlNode<E> node) { if (right == null) { return left; } else { right = right.removeMax(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } private void recomputeMultiset() { this.distinctElements = 1 + TreeMultiset.distinctElements(left) + TreeMultiset.distinctElements(right); this.totalCount = elemCount + totalCount(left) + totalCount(right); } private void recomputeHeight() { this.height = 1 + Math.max(height(left), height(right)); } private void recompute() { recomputeMultiset(); recomputeHeight(); } private AvlNode<E> rebalance() { switch (balanceFactor()) { case -2: if (right.balanceFactor() > 0) { right = right.rotateRight(); } return rotateLeft(); case 2: if (left.balanceFactor() < 0) { left = left.rotateLeft(); } return rotateRight(); default: recomputeHeight(); return this; } } private int balanceFactor() { return height(left) - height(right); } private AvlNode<E> rotateLeft() { checkState(right != null); AvlNode<E> newTop = right; this.right = newTop.left; newTop.left = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private AvlNode<E> rotateRight() { checkState(left != null); AvlNode<E> newTop = left; this.left = newTop.right; newTop.right = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private static long totalCount(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.totalCount; } private static int height(@Nullable AvlNode<?> node) { return (node == null) ? 0 : node.height; } @Nullable private AvlNode<E> ceiling(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp < 0) { return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this); } else if (cmp == 0) { return this; } else { return (right == null) ? null : right.ceiling(comparator, e); } } @Nullable private AvlNode<E> floor(Comparator<? super E> comparator, E e) { int cmp = comparator.compare(e, elem); if (cmp > 0) { return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this); } else if (cmp == 0) { return this; } else { return (left == null) ? null : left.floor(comparator, e); } } @Override public E getElement() { return elem; } @Override public int getCount() { return elemCount; } @Override public String toString() { return Multisets.immutableEntry(getElement(), getCount()).toString(); } } private static <T> void successor(AvlNode<T> a, AvlNode<T> b) { a.succ = b; b.pred = a; } private static <T> void successor(AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) { successor(a, b); successor(b, c); } /* * TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that * calls the comparator to compare the two keys. If that change is made, * AbstractMultiset.equals() can simply check whether two multisets have equal entry sets. */ /** * @serialData the comparator, the number of distinct elements, the first element, its count, the * second element, its count, and so on */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(elementSet().comparator()); Serialization.writeMultiset(this, stream); } @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject Comparator<? super E> comparator = (Comparator<? super E>) stream.readObject(); Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); Serialization.getFieldSetter(TreeMultiset.class, "range").set( this, GeneralRange.all(comparator)); Serialization.getFieldSetter(TreeMultiset.class, "rootReference").set( this, new Reference<AvlNode<E>>()); AvlNode<E> header = new AvlNode<E>(null, 1); Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); successor(header, header); Serialization.populateMultiset(this, stream); } @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 1; }
Java
/* * Copyright (C) 2013 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 com.google.common.annotations.GwtIncompatible; import javax.annotation.Nullable; /** * Implementation of {@code Map.Entry} for {@link ImmutableMap} that adds extra methods to traverse * hash buckets for the key and the value. This allows reuse in {@link RegularImmutableMap} and * {@link RegularImmutableBiMap}, which don't have to recopy the entries created by their * {@code Builder} implementations. * * @author Louis Wasserman */ @GwtIncompatible("unnecessary") abstract class ImmutableMapEntry<K, V> extends ImmutableEntry<K, V> { ImmutableMapEntry(K key, V value) { super(key, value); ImmutableMap.checkEntryNotNull(key, value); } ImmutableMapEntry(ImmutableMapEntry<K, V> contents) { super(contents.getKey(), contents.getValue()); // null check would be redundant } @Nullable abstract ImmutableMapEntry<K, V> getNextInKeyBucket(); @Nullable abstract ImmutableMapEntry<K, V> getNextInValueBucket(); static final class TerminalEntry<K, V> extends ImmutableMapEntry<K, V> { TerminalEntry(ImmutableMapEntry<K, V> contents) { super(contents); } TerminalEntry(K key, V value) { super(key, value); } @Override @Nullable ImmutableMapEntry<K, V> getNextInKeyBucket() { return null; } @Override @Nullable ImmutableMapEntry<K, V> getNextInValueBucket() { return null; } } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; /** * Implementation of {@link ImmutableSet} with two or more elements. * * @author Kevin Bourrillion */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class RegularImmutableSet<E> extends ImmutableSet<E> { private final Object[] elements; // the same elements in hashed positions (plus nulls) @VisibleForTesting final transient Object[] table; // 'and' with an int to get a valid table index. private final transient int mask; private final transient int hashCode; RegularImmutableSet( Object[] elements, int hashCode, Object[] table, int mask) { this.elements = elements; this.table = table; this.mask = mask; this.hashCode = hashCode; } @Override public boolean contains(Object target) { if (target == null) { return false; } for (int i = Hashing.smear(target.hashCode()); true; i++) { Object candidate = table[i & mask]; if (candidate == null) { return false; } if (candidate.equals(target)) { return true; } } } @Override public int size() { return elements.length; } @SuppressWarnings("unchecked") // all elements are E's @Override public UnmodifiableIterator<E> iterator() { return (UnmodifiableIterator<E>) Iterators.forArray(elements); } @Override int copyIntoArray(Object[] dst, int offset) { System.arraycopy(elements, 0, dst, offset, elements.length); return offset + elements.length; } @Override ImmutableList<E> createAsList() { return new RegularImmutableAsList<E>(this, elements); } @Override boolean isPartialView() { return false; } @Override public int hashCode() { return hashCode; } @Override boolean isHashCodeFast() { return true; } }
Java
/* * Copyright (C) 2013 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 com.google.common.annotations.GwtCompatible; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Skeletal, implementation-agnostic implementation of the {@link Table} interface. * * @author Louis Wasserman */ @GwtCompatible abstract class AbstractTable<R, C, V> implements Table<R, C, V> { @Override public boolean containsRow(@Nullable Object rowKey) { return Maps.safeContainsKey(rowMap(), rowKey); } @Override public boolean containsColumn(@Nullable Object columnKey) { return Maps.safeContainsKey(columnMap(), columnKey); } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } @Override public Set<C> columnKeySet() { return columnMap().keySet(); } @Override public boolean containsValue(@Nullable Object value) { for (Map<C, V> row : rowMap().values()) { if (row.containsValue(value)) { return true; } } return false; } @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return row != null && Maps.safeContainsKey(row, columnKey); } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeGet(row, columnKey); } @Override public boolean isEmpty() { return size() == 0; } @Override public void clear() { Iterators.clear(cellSet().iterator()); } @Override public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeRemove(row, columnKey); } @Override public V put(R rowKey, C columnKey, V value) { return row(rowKey).put(columnKey, value); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { for (Table.Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) { put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } } private transient Set<Cell<R, C, V>> cellSet; @Override public Set<Cell<R, C, V>> cellSet() { Set<Cell<R, C, V>> result = cellSet; return (result == null) ? cellSet = createCellSet() : result; } Set<Cell<R, C, V>> createCellSet() { return new CellSet(); } abstract Iterator<Table.Cell<R, C, V>> cellIterator(); class CellSet extends AbstractSet<Cell<R, C, V>> { @Override public boolean contains(Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeContains( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public boolean remove(@Nullable Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeRemove( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public void clear() { AbstractTable.this.clear(); } @Override public Iterator<Table.Cell<R, C, V>> iterator() { return cellIterator(); } @Override public int size() { return AbstractTable.this.size(); } } private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values(); } Iterator<V> valuesIterator() { return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) { @Override V transform(Cell<R, C, V> cell) { return cell.getValue(); } }; } class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return valuesIterator(); } @Override public boolean contains(Object o) { return containsValue(o); } @Override public void clear() { AbstractTable.this.clear(); } @Override public int size() { return AbstractTable.this.size(); } } @Override public boolean equals(@Nullable Object obj) { return Tables.equalsImpl(this, obj); } @Override public int hashCode() { return cellSet().hashCode(); } /** * Returns the string representation {@code rowMap().toString()}. */ @Override public String toString() { return rowMap().toString(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Multisets.checkNonnegative; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Serialization.FieldSetter; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; /** * A multiset that supports concurrent modifications and that provides atomic versions of most * {@code Multiset} operations (exceptions where noted). Null elements are not supported. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Cliff L. Biffle * @author mike nonemacher * @since 2.0 (imported from Google Collections Library) */ public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable { /* * The ConcurrentHashMultiset's atomic operations are implemented primarily in terms of * AtomicInteger's atomic operations, with some help from ConcurrentMap's atomic operations on * creation and removal (including automatic removal of zeroes). If the modification of an * AtomicInteger results in zero, we compareAndSet the value to zero; if that succeeds, we remove * the entry from the Map. If another operation sees a zero in the map, it knows that the entry is * about to be removed, so this operation may remove it (often by replacing it with a new * AtomicInteger). */ /** The number of occurrences of each element. */ private final transient ConcurrentMap<E, AtomicInteger> countMap; // This constant allows the deserialization code to set a final field. This holder class // makes sure it is not initialized unless an instance is deserialized. private static class FieldSettersHolder { static final FieldSetter<ConcurrentHashMultiset> COUNT_MAP_FIELD_SETTER = Serialization.getFieldSetter(ConcurrentHashMultiset.class, "countMap"); } /** * Creates a new, empty {@code ConcurrentHashMultiset} using the default * initial capacity, load factor, and concurrency settings. */ public static <E> ConcurrentHashMultiset<E> create() { // TODO(schmoe): provide a way to use this class with other (possibly arbitrary) // ConcurrentMap implementors. One possibility is to extract most of this class into // an AbstractConcurrentMapMultiset. return new ConcurrentHashMultiset<E>(new ConcurrentHashMap<E, AtomicInteger>()); } /** * Creates a new {@code ConcurrentHashMultiset} containing the specified elements, using * the default initial capacity, load factor, and concurrency settings. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}. * * @param elements the elements that the multiset should contain */ public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) { ConcurrentHashMultiset<E> multiset = ConcurrentHashMultiset.create(); Iterables.addAll(multiset, elements); return multiset; } /** * Creates a new, empty {@code ConcurrentHashMultiset} using {@code mapMaker} * to construct the internal backing map. * * <p>If this {@link MapMaker} is configured to use entry eviction of any kind, this eviction * applies to all occurrences of a given element as a single unit. However, most updates to the * multiset do not count as map updates at all, since we're usually just mutating the value * stored in the map, so {@link MapMaker#expireAfterAccess} makes sense (evict the entry that * was queried or updated longest ago), but {@link MapMaker#expireAfterWrite} doesn't, because * the eviction time is measured from when we saw the first occurrence of the object. * * <p>The returned multiset is serializable but any serialization caveats * given in {@code MapMaker} apply. * * <p>Finally, soft/weak values can be used but are not very useful: the values are created * internally and not exposed externally, so no one else will have a strong reference to the * values. Weak keys on the other hand can be useful in some scenarios. * * @since 15.0 (source compatible (accepting the since removed {@code GenericMapMaker} class) * since 7.0) */ @Beta public static <E> ConcurrentHashMultiset<E> create(MapMaker mapMaker) { return new ConcurrentHashMultiset<E>(mapMaker.<E, AtomicInteger>makeMap()); } /** * Creates an instance using {@code countMap} to store elements and their counts. * * <p>This instance will assume ownership of {@code countMap}, and other code * should not maintain references to the map or modify it in any way. * * @param countMap backing map for storing the elements in the multiset and * their counts. It must be empty. * @throws IllegalArgumentException if {@code countMap} is not empty */ @VisibleForTesting ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) { checkArgument(countMap.isEmpty()); this.countMap = countMap; } // Query Operations /** * Returns the number of occurrences of {@code element} in this multiset. * * @param element the element to look for * @return the nonnegative number of occurrences of the element */ @Override public int count(@Nullable Object element) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); return (existingCounter == null) ? 0 : existingCounter.get(); } /** * {@inheritDoc} * * <p>If the data in the multiset is modified by any other threads during this method, * it is undefined which (if any) of these modifications will be reflected in the result. */ @Override public int size() { long sum = 0L; for (AtomicInteger value : countMap.values()) { sum += value.get(); } return Ints.saturatedCast(sum); } /* * Note: the superclass toArray() methods assume that size() gives a correct * answer, which ours does not. */ @Override public Object[] toArray() { return snapshot().toArray(); } @Override public <T> T[] toArray(T[] array) { return snapshot().toArray(array); } /* * We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but * either of these would recurse back to us again! */ private List<E> snapshot() { List<E> list = Lists.newArrayListWithExpectedSize(size()); for (Multiset.Entry<E> entry : entrySet()) { E element = entry.getElement(); for (int i = entry.getCount(); i > 0; i--) { list.add(element); } } return list; } // Modification Operations /** * Adds a number of occurrences of the specified element to this multiset. * * @param element the element to add * @param occurrences the number of occurrences to add * @return the previous count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if * the resulting amount would exceed {@link Integer#MAX_VALUE} */ @Override public int add(E element, int occurrences) { checkNotNull(element); if (occurrences == 0) { return count(element); } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through to operate against the existing AtomicInteger } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { try { int newValue = IntMath.checkedAdd(oldValue, occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { // newValue can't == 0, so no need to check & remove return oldValue; } } catch (ArithmeticException overflow) { throw new IllegalArgumentException("Overflow adding " + occurrences + " occurrences to a count of " + oldValue); } } else { // In the case of a concurrent remove, we might observe a zero value, which means another // thread is about to remove (element, existingCounter) from the map. Rather than wait, // we can just do that work here. AtomicInteger newCounter = new AtomicInteger(occurrences); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } break; } } // If we're still here, there was a race, so just try again. } } /** * Removes a number of occurrences of the specified element from this multiset. If the multiset * contains fewer than this number of occurrences to begin with, all occurrences will be removed. * * @param element the element whose occurrences should be removed * @param occurrences the number of occurrences of the element to remove * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ /* * TODO(cpovirk): remove and removeExactly currently accept null inputs only * if occurrences == 0. This satisfies both NullPointerTester and * CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's * a good policy, especially because, in order for the test to pass, the * parameter must be misleadingly annotated as @Nullable. I suspect that * we'll want to remove @Nullable, add an eager checkNotNull, and loosen up * testRemove_nullAllowed. */ @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { return count(element); } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { return 0; } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { int newValue = Math.max(0, oldValue - occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { if (newValue == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } else { return 0; } } } /** * Removes exactly the specified number of occurrences of {@code element}, or makes no * change if this is not possible. * * <p>This method, in contrast to {@link #remove(Object, int)}, has no effect when the * element count is smaller than {@code occurrences}. * * @param element the element to remove * @param occurrences the number of occurrences of {@code element} to remove * @return {@code true} if the removal was possible (including if {@code occurrences} is zero) */ public boolean removeExactly(@Nullable Object element, int occurrences) { if (occurrences == 0) { return true; } checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { return false; } while (true) { int oldValue = existingCounter.get(); if (oldValue < occurrences) { return false; } int newValue = oldValue - occurrences; if (existingCounter.compareAndSet(oldValue, newValue)) { if (newValue == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return true; } } } /** * Adds or removes occurrences of {@code element} such that the {@link #count} of the * element becomes {@code count}. * * @return the count of {@code element} in the multiset before this call * @throws IllegalArgumentException if {@code count} is negative */ @Override public int setCount(E element, int count) { checkNotNull(element); checkNonnegative(count, "count"); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { if (count == 0) { return 0; } else { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through } } while (true) { int oldValue = existingCounter.get(); if (oldValue == 0) { if (count == 0) { return 0; } else { AtomicInteger newCounter = new AtomicInteger(count); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } } break; } else { if (existingCounter.compareAndSet(oldValue, count)) { if (count == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } } } } /** * Sets the number of occurrences of {@code element} to {@code newCount}, but only if * the count is currently {@code expectedOldCount}. If {@code element} does not appear * in the multiset exactly {@code expectedOldCount} times, no changes will be made. * * @return {@code true} if the change was successful. This usually indicates * that the multiset has been modified, but not always: in the case that * {@code expectedOldCount == newCount}, the method will return {@code true} if * the condition was met. * @throws IllegalArgumentException if {@code expectedOldCount} or {@code newCount} is negative */ @Override public boolean setCount(E element, int expectedOldCount, int newCount) { checkNotNull(element); checkNonnegative(expectedOldCount, "oldCount"); checkNonnegative(newCount, "newCount"); AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { if (expectedOldCount != 0) { return false; } else if (newCount == 0) { return true; } else { // if our write lost the race, it must have lost to a nonzero value, so we can stop return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null; } } int oldValue = existingCounter.get(); if (oldValue == expectedOldCount) { if (oldValue == 0) { if (newCount == 0) { // Just observed a 0; try to remove the entry to clean up the map countMap.remove(element, existingCounter); return true; } else { AtomicInteger newCounter = new AtomicInteger(newCount); return (countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter); } } else { if (existingCounter.compareAndSet(oldValue, newCount)) { if (newCount == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return true; } } } return false; } // Views @Override Set<E> createElementSet() { final Set<E> delegate = countMap.keySet(); return new ForwardingSet<E>() { @Override protected Set<E> delegate() { return delegate; } @Override public boolean contains(@Nullable Object object) { return object != null && Collections2.safeContains(delegate, object); } @Override public boolean containsAll(Collection<?> collection) { return standardContainsAll(collection); } @Override public boolean remove(Object object) { return object != null && Collections2.safeRemove(delegate, object); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } }; } private transient EntrySet entrySet; @Override public Set<Multiset.Entry<E>> entrySet() { EntrySet result = entrySet; if (result == null) { entrySet = result = new EntrySet(); } return result; } @Override int distinctElements() { return countMap.size(); } @Override public boolean isEmpty() { return countMap.isEmpty(); } @Override Iterator<Entry<E>> entryIterator() { // AbstractIterator makes this fairly clean, but it doesn't support remove(). To support // remove(), we create an AbstractIterator, and then use ForwardingIterator to delegate to it. final Iterator<Entry<E>> readOnlyIterator = new AbstractIterator<Entry<E>>() { private Iterator<Map.Entry<E, AtomicInteger>> mapEntries = countMap.entrySet().iterator(); @Override protected Entry<E> computeNext() { while (true) { if (!mapEntries.hasNext()) { return endOfData(); } Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next(); int count = mapEntry.getValue().get(); if (count != 0) { return Multisets.immutableEntry(mapEntry.getKey(), count); } } } }; return new ForwardingIterator<Entry<E>>() { private Entry<E> last; @Override protected Iterator<Entry<E>> delegate() { return readOnlyIterator; } @Override public Entry<E> next() { last = super.next(); return last; } @Override public void remove() { checkState(last != null); ConcurrentHashMultiset.this.setCount(last.getElement(), 0); last = null; } }; } @Override public void clear() { countMap.clear(); } private class EntrySet extends AbstractMultiset<E>.EntrySet { @Override ConcurrentHashMultiset<E> multiset() { return ConcurrentHashMultiset.this; } /* * Note: the superclass toArray() methods assume that size() gives a correct * answer, which ours does not. */ @Override public Object[] toArray() { return snapshot().toArray(); } @Override public <T> T[] toArray(T[] array) { return snapshot().toArray(array); } private List<Multiset.Entry<E>> snapshot() { List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size()); // Not Iterables.addAll(list, this), because that'll forward right back here. Iterators.addAll(list, iterator()); return list; } } /** * @serialData the ConcurrentMap of elements and their counts. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(countMap); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject ConcurrentMap<E, Integer> deserializedCountMap = (ConcurrentMap<E, Integer>) stream.readObject(); FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap); } private static final long serialVersionUID = 1; }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.List; import javax.annotation.Nullable; /** An ordering that compares objects according to a given order. */ @GwtCompatible(serializable = true) final class ExplicitOrdering<T> extends Ordering<T> implements Serializable { final ImmutableMap<T, Integer> rankMap; ExplicitOrdering(List<T> valuesInOrder) { this(buildRankMap(valuesInOrder)); } ExplicitOrdering(ImmutableMap<T, Integer> rankMap) { this.rankMap = rankMap; } @Override public int compare(T left, T right) { return rank(left) - rank(right); // safe because both are nonnegative } private int rank(T value) { Integer rank = rankMap.get(value); if (rank == null) { throw new IncomparableValueException(value); } return rank; } private static <T> ImmutableMap<T, Integer> buildRankMap( List<T> valuesInOrder) { ImmutableMap.Builder<T, Integer> builder = ImmutableMap.builder(); int rank = 0; for (T value : valuesInOrder) { builder.put(value, rank++); } return builder.build(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof ExplicitOrdering) { ExplicitOrdering<?> that = (ExplicitOrdering<?>) object; return this.rankMap.equals(that.rankMap); } return false; } @Override public int hashCode() { return rankMap.hashCode(); } @Override public String toString() { return "Ordering.explicit(" + rankMap.keySet() + ")"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2012 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.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.collect.SortedLists.KeyAbsentBehavior; import com.google.common.collect.SortedLists.KeyPresentBehavior; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import javax.annotation.Nullable; /** * An immutable implementation of {@code RangeMap}, supporting all query operations efficiently. * * <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtIncompatible("NavigableMap") public class ImmutableRangeMap<K extends Comparable<?>, V> implements RangeMap<K, V> { @SuppressWarnings("unchecked") private static final ImmutableRangeMap EMPTY = new ImmutableRangeMap(ImmutableList.of(), ImmutableList.of()); /** * Returns an empty immutable range map. */ @SuppressWarnings("unchecked") public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of() { return EMPTY; } /** * Returns an immutable range map mapping a single range to a single value. */ public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> of( Range<K> range, V value) { return new ImmutableRangeMap<K, V>(ImmutableList.of(range), ImmutableList.of(value)); } @SuppressWarnings("unchecked") public static <K extends Comparable<?>, V> ImmutableRangeMap<K, V> copyOf( RangeMap<K, ? extends V> rangeMap) { if (rangeMap instanceof ImmutableRangeMap) { return (ImmutableRangeMap<K, V>) rangeMap; } Map<Range<K>, ? extends V> map = rangeMap.asMapOfRanges(); ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<Range<K>>(map.size()); ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<V>(map.size()); for (Entry<Range<K>, ? extends V> entry : map.entrySet()) { rangesBuilder.add(entry.getKey()); valuesBuilder.add(entry.getValue()); } return new ImmutableRangeMap<K, V>(rangesBuilder.build(), valuesBuilder.build()); } /** * Returns a new builder for an immutable range map. */ public static <K extends Comparable<?>, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for immutable range maps. Overlapping ranges are prohibited. */ public static final class Builder<K extends Comparable<?>, V> { private final RangeSet<K> keyRanges; private final RangeMap<K, V> rangeMap; public Builder() { this.keyRanges = TreeRangeSet.create(); this.rangeMap = TreeRangeMap.create(); } /** * Associates the specified range with the specified value. * * @throws IllegalArgumentException if {@code range} overlaps with any other ranges inserted * into this builder, or if {@code range} is empty */ public Builder<K, V> put(Range<K> range, V value) { checkNotNull(range); checkNotNull(value); checkArgument(!range.isEmpty(), "Range must not be empty, but was %s", range); if (!keyRanges.complement().encloses(range)) { // it's an error case; we can afford an expensive lookup for (Entry<Range<K>, V> entry : rangeMap.asMapOfRanges().entrySet()) { Range<K> key = entry.getKey(); if (key.isConnected(range) && !key.intersection(range).isEmpty()) { throw new IllegalArgumentException( "Overlapping ranges: range " + range + " overlaps with entry " + entry); } } } keyRanges.add(range); rangeMap.put(range, value); return this; } /** * Copies all associations from the specified range map into this builder. * * @throws IllegalArgumentException if any of the ranges in {@code rangeMap} overlap with ranges * already in this builder */ public Builder<K, V> putAll(RangeMap<K, ? extends V> rangeMap) { for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) { put(entry.getKey(), entry.getValue()); } return this; } /** * Returns an {@code ImmutableRangeMap} containing the associations previously added to this * builder. */ public ImmutableRangeMap<K, V> build() { Map<Range<K>, V> map = rangeMap.asMapOfRanges(); ImmutableList.Builder<Range<K>> rangesBuilder = new ImmutableList.Builder<Range<K>>(map.size()); ImmutableList.Builder<V> valuesBuilder = new ImmutableList.Builder<V>(map.size()); for (Entry<Range<K>, V> entry : map.entrySet()) { rangesBuilder.add(entry.getKey()); valuesBuilder.add(entry.getValue()); } return new ImmutableRangeMap<K, V>(rangesBuilder.build(), valuesBuilder.build()); } } private final ImmutableList<Range<K>> ranges; private final ImmutableList<V> values; ImmutableRangeMap(ImmutableList<Range<K>> ranges, ImmutableList<V> values) { this.ranges = ranges; this.values = values; } @Override @Nullable public V get(K key) { int index = SortedLists.binarySearch(ranges, Range.<K>lowerBoundFn(), Cut.belowValue(key), KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_LOWER); if (index == -1) { return null; } else { Range<K> range = ranges.get(index); return range.contains(key) ? values.get(index) : null; } } @Override @Nullable public Map.Entry<Range<K>, V> getEntry(K key) { int index = SortedLists.binarySearch(ranges, Range.<K>lowerBoundFn(), Cut.belowValue(key), KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_LOWER); if (index == -1) { return null; } else { Range<K> range = ranges.get(index); return range.contains(key) ? Maps.immutableEntry(range, values.get(index)) : null; } } @Override public Range<K> span() { if (ranges.isEmpty()) { throw new NoSuchElementException(); } Range<K> firstRange = ranges.get(0); Range<K> lastRange = ranges.get(ranges.size() - 1); return Range.create(firstRange.lowerBound, lastRange.upperBound); } @Override public void put(Range<K> range, V value) { throw new UnsupportedOperationException(); } @Override public void putAll(RangeMap<K, V> rangeMap) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public void remove(Range<K> range) { throw new UnsupportedOperationException(); } @Override public ImmutableMap<Range<K>, V> asMapOfRanges() { if (ranges.isEmpty()) { return ImmutableMap.of(); } RegularImmutableSortedSet<Range<K>> rangeSet = new RegularImmutableSortedSet<Range<K>>(ranges, Range.RANGE_LEX_ORDERING); return new RegularImmutableSortedMap<Range<K>, V>(rangeSet, values); } @Override public ImmutableRangeMap<K, V> subRangeMap(final Range<K> range) { if (checkNotNull(range).isEmpty()) { return ImmutableRangeMap.of(); } else if (ranges.isEmpty() || range.encloses(span())) { return this; } int lowerIndex = SortedLists.binarySearch( ranges, Range.<K>upperBoundFn(), range.lowerBound, KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER); int upperIndex = SortedLists.binarySearch(ranges, Range.<K>lowerBoundFn(), range.upperBound, KeyPresentBehavior.ANY_PRESENT, KeyAbsentBehavior.NEXT_HIGHER); if (lowerIndex >= upperIndex) { return ImmutableRangeMap.of(); } final int off = lowerIndex; final int len = upperIndex - lowerIndex; ImmutableList<Range<K>> subRanges = new ImmutableList<Range<K>>() { @Override public int size() { return len; } @Override public Range<K> get(int index) { checkElementIndex(index, len); if (index == 0 || index == len - 1) { return ranges.get(index + off).intersection(range); } else { return ranges.get(index + off); } } @Override boolean isPartialView() { return true; } }; final ImmutableRangeMap<K, V> outer = this; return new ImmutableRangeMap<K, V>( subRanges, values.subList(lowerIndex, upperIndex)) { @Override public ImmutableRangeMap<K, V> subRangeMap(Range<K> subRange) { if (range.isConnected(subRange)) { return outer.subRangeMap(subRange.intersection(range)); } else { return ImmutableRangeMap.of(); } } }; } @Override public int hashCode() { return asMapOfRanges().hashCode(); } @Override public boolean equals(@Nullable Object o) { if (o instanceof RangeMap) { RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o; return asMapOfRanges().equals(rangeMap.asMapOfRanges()); } return false; } @Override public String toString() { return asMapOfRanges().toString(); } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMapEntry.TerminalEntry; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableMap} with two or more entries. * * @author Jesse Wilson * @author Kevin Bourrillion * @author Gregory Kick */ @GwtCompatible(serializable = true, emulated = true) final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> { // entries in insertion order private final transient ImmutableMapEntry<K, V>[] entries; // array of linked lists of entries private final transient ImmutableMapEntry<K, V>[] table; // 'and' with an int to get a table index private final transient int mask; RegularImmutableMap(TerminalEntry<?, ?>... theEntries) { this(theEntries.length, theEntries); } /** * Constructor for RegularImmutableMap that takes as input an array of {@code TerminalEntry} * entries. Assumes that these entries have already been checked for null. * * <p>This allows reuse of the entry objects from the array in the actual implementation. */ RegularImmutableMap(int size, TerminalEntry<?, ?>[] theEntries) { entries = createEntryArray(size); int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR); table = createEntryArray(tableSize); mask = tableSize - 1; for (int entryIndex = 0; entryIndex < size; entryIndex++) { @SuppressWarnings("unchecked") TerminalEntry<K, V> entry = (TerminalEntry<K, V>) theEntries[entryIndex]; K key = entry.getKey(); int tableIndex = Hashing.smear(key.hashCode()) & mask; @Nullable ImmutableMapEntry<K, V> existing = table[tableIndex]; // prepend, not append, so the entries can be immutable ImmutableMapEntry<K, V> newEntry = (existing == null) ? entry : new NonTerminalMapEntry<K, V>(entry, existing); table[tableIndex] = newEntry; entries[entryIndex] = newEntry; checkNoConflictInBucket(key, newEntry, existing); } } /** * Constructor for RegularImmutableMap that makes no assumptions about the input entries. */ RegularImmutableMap(Entry<?, ?>[] theEntries) { int size = theEntries.length; entries = createEntryArray(size); int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR); table = createEntryArray(tableSize); mask = tableSize - 1; for (int entryIndex = 0; entryIndex < size; entryIndex++) { @SuppressWarnings("unchecked") // all our callers carefully put in only Entry<K, V>s Entry<K, V> entry = (Entry<K, V>) theEntries[entryIndex]; K key = entry.getKey(); V value = entry.getValue(); checkEntryNotNull(key, value); int tableIndex = Hashing.smear(key.hashCode()) & mask; @Nullable ImmutableMapEntry<K, V> existing = table[tableIndex]; // prepend, not append, so the entries can be immutable ImmutableMapEntry<K, V> newEntry = (existing == null) ? new TerminalEntry<K, V>(key, value) : new NonTerminalMapEntry<K, V>(key, value, existing); table[tableIndex] = newEntry; entries[entryIndex] = newEntry; checkNoConflictInBucket(key, newEntry, existing); } } private void checkNoConflictInBucket( K key, ImmutableMapEntry<K, V> entry, ImmutableMapEntry<K, V> bucketHead) { for (; bucketHead != null; bucketHead = bucketHead.getNextInKeyBucket()) { checkNoConflict(!key.equals(bucketHead.getKey()), "key", entry, bucketHead); } } private static final class NonTerminalMapEntry<K, V> extends ImmutableMapEntry<K, V> { private final ImmutableMapEntry<K, V> nextInKeyBucket; NonTerminalMapEntry(K key, V value, ImmutableMapEntry<K, V> nextInKeyBucket) { super(key, value); this.nextInKeyBucket = nextInKeyBucket; } NonTerminalMapEntry(ImmutableMapEntry<K, V> contents, ImmutableMapEntry<K, V> nextInKeyBucket) { super(contents); this.nextInKeyBucket = nextInKeyBucket; } @Override ImmutableMapEntry<K, V> getNextInKeyBucket() { return nextInKeyBucket; } @Override @Nullable ImmutableMapEntry<K, V> getNextInValueBucket() { return null; } } /** * Closed addressing tends to perform well even with high load factors. * Being conservative here ensures that the table is still likely to be * relatively sparse (hence it misses fast) while saving space. */ private static final double MAX_LOAD_FACTOR = 1.2; /** * Creates an {@code ImmutableMapEntry} array to hold parameterized entries. The * result must never be upcast back to ImmutableMapEntry[] (or Object[], etc.), or * allowed to escape the class. */ @SuppressWarnings("unchecked") // Safe as long as the javadocs are followed private ImmutableMapEntry<K, V>[] createEntryArray(int size) { return new ImmutableMapEntry[size]; } @Override public V get(@Nullable Object key) { if (key == null) { return null; } int index = Hashing.smear(key.hashCode()) & mask; for (ImmutableMapEntry<K, V> entry = table[index]; entry != null; entry = entry.getNextInKeyBucket()) { K candidateKey = entry.getKey(); /* * Assume that equals uses the == optimization when appropriate, and that * it would check hash codes as an optimization when appropriate. If we * did these things, it would just make things worse for the most * performance-conscious users. */ if (key.equals(candidateKey)) { return entry.getValue(); } } return null; } @Override public int size() { return entries.length; } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new EntrySet(); } @SuppressWarnings("serial") // uses writeReplace(), not default serialization private class EntrySet extends ImmutableMapEntrySet<K, V> { @Override ImmutableMap<K, V> map() { return RegularImmutableMap.this; } @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return asList().iterator(); } @Override ImmutableList<Entry<K, V>> createAsList() { return new RegularImmutableAsList<Entry<K, V>>(this, entries); } } // This class is never actually serialized directly, but we have to make the // warning go away (and suppressing would suppress for all nested classes too) private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.SortedSet; import javax.annotation.Nullable; /** * A sorted set multimap which forwards all its method calls to another sorted * set multimap. Subclasses should override one or more methods to modify the * behavior of the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 3.0 */ @GwtCompatible public abstract class ForwardingSortedSetMultimap<K, V> extends ForwardingSetMultimap<K, V> implements SortedSetMultimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingSortedSetMultimap() {} @Override protected abstract SortedSetMultimap<K, V> delegate(); @Override public SortedSet<V> get(@Nullable K key) { return delegate().get(key); } @Override public SortedSet<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } @Override public Comparator<? super V> valueComparator() { return delegate().valueComparator(); } }
Java
/* * Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible; import java.util.ListIterator; /** * A list iterator that does not support {@link #remove}, {@link #add}, or * {@link #set}. * * @since 7.0 * @author Louis Wasserman */ @GwtCompatible public abstract class UnmodifiableListIterator<E> extends UnmodifiableIterator<E> implements ListIterator<E> { /** Constructor for use by subclasses. */ protected UnmodifiableListIterator() {} /** * Guaranteed to throw an exception and leave the underlying data unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void add(E e) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the underlying data unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void set(E e) { throw new UnsupportedOperationException(); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; /** * Unused stub class, unreferenced under Java and manually emulated under GWT. * * @author Chris Povirk */ @GwtCompatible(emulated = true) abstract class ForwardingImmutableSet<E> { private ForwardingImmutableSet() {} }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.SortedMap; import java.util.SortedSet; /** * Basic implementation of a {@link SortedSetMultimap} with a sorted key set. * * This superclass allows {@code TreeMultimap} to override methods to return * navigable set and map types in non-GWT only, while GWT code will inherit the * SortedMap/SortedSet overrides. * * @author Louis Wasserman */ @GwtCompatible abstract class AbstractSortedKeySortedSetMultimap<K, V> extends AbstractSortedSetMultimap<K, V> { AbstractSortedKeySortedSetMultimap(SortedMap<K, Collection<V>> map) { super(map); } @Override public SortedMap<K, Collection<V>> asMap() { return (SortedMap<K, Collection<V>>) super.asMap(); } @Override SortedMap<K, Collection<V>> backingMap() { return (SortedMap<K, Collection<V>>) super.backingMap(); } @Override public SortedSet<K> keySet() { return (SortedSet<K>) super.keySet(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.compose; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Joiner.MapJoiner; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.MapDifference.ValueDifference; import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Enumeration; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@link Map} instances (including instances of * {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts * {@link Lists}, {@link Sets} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Maps"> * {@code Maps}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Isaac Shum * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Maps { private Maps() {} private enum EntryFunction implements Function<Entry<?, ?>, Object> { KEY { @Override @Nullable public Object apply(Entry<?, ?> entry) { return entry.getKey(); } }, VALUE { @Override @Nullable public Object apply(Entry<?, ?> entry) { return entry.getValue(); } }; } @SuppressWarnings("unchecked") static <K> Function<Entry<K, ?>, K> keyFunction() { return (Function) EntryFunction.KEY; } @SuppressWarnings("unchecked") static <V> Function<Entry<?, V>, V> valueFunction() { return (Function) EntryFunction.VALUE; } static <K, V> Iterator<K> keyIterator(Iterator<Entry<K, V>> entryIterator) { return Iterators.transform(entryIterator, Maps.<K>keyFunction()); } static <K, V> Iterator<V> valueIterator(Iterator<Entry<K, V>> entryIterator) { return Iterators.transform(entryIterator, Maps.<V>valueFunction()); } static <K, V> UnmodifiableIterator<V> valueIterator( final UnmodifiableIterator<Entry<K, V>> entryIterator) { return new UnmodifiableIterator<V>() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public V next() { return entryIterator.next().getValue(); } }; } /** * Returns an immutable map instance containing the given entries. * Internally, the returned map will be backed by an {@link EnumMap}. * * <p>The iteration order of the returned map follows the enum's iteration * order, not the order in which the elements appear in the given map. * * @param map the map to make an immutable copy of * @return an immutable map containing those entries * @since 14.0 */ @GwtCompatible(serializable = true) @Beta public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap( Map<K, ? extends V> map) { if (map instanceof ImmutableEnumMap) { @SuppressWarnings("unchecked") // safe covariant cast ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map; return result; } else if (map.isEmpty()) { return ImmutableMap.of(); } else { for (Map.Entry<K, ? extends V> entry : map.entrySet()) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); } return ImmutableEnumMap.asImmutable(new EnumMap<K, V>(map)); } } /** * Creates a <i>mutable</i>, empty {@code HashMap} instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#of()} instead. * * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link * #newEnumMap} instead. * * @return a new, empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@code HashMap} instance, with a high enough "initial capacity" * that it <i>should</i> hold {@code 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 <i>oversizing</i> the returned map. * * @param expectedSize the number of elements you expect to add to the * returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code 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 < Ints.MAX_POWER_OF_TWO) { return expectedSize + expectedSize / 3; } return Integer.MAX_VALUE; // any large value } /** * Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as * the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * * <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link * #newEnumMap} instead. * * @param map the mappings to be placed in the new map * @return a new {@code HashMap} initialized with the mappings from {@code * map} */ public static <K, V> HashMap<K, V> newHashMap( Map<? extends K, ? extends V> map) { return new HashMap<K, V>(map); } /** * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} * instance. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#of()} instead. * * @return a new, empty {@code LinkedHashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<K, V>(); } /** * Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance * with the same mappings as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * * @param map the mappings to be placed in the new map * @return a new, {@code LinkedHashMap} initialized with the mappings from * {@code 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 {@code ConcurrentMap}, which supports * all optional operations of the ConcurrentMap interface. It does not permit * null keys or values. It is serializable. * * <p>This is currently accomplished by calling {@link MapMaker#makeMap()}. * * <p>It is preferable to use {@code 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. * * @return a new, empty {@code ConcurrentMap} * @since 3.0 */ public static <K, V> ConcurrentMap<K, V> newConcurrentMap() { return new MapMaker().<K, V>makeMap(); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural * ordering of its elements. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedMap#of()} instead. * * @return a new, empty {@code TreeMap} */ public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() { return new TreeMap<K, V>(); } /** * Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as * the specified map and using the same ordering as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedMap#copyOfSorted(SortedMap)} instead. * * @param 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 * @return a new {@code TreeMap} initialized with the mappings from {@code * map} and using the comparator of {@code map} */ public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) { return new TreeMap<K, V>(map); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given * comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedMap.orderedBy(comparator).build()} instead. * * @param comparator the comparator to sort the keys with * @return a new, empty {@code 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 {@code EnumMap} instance. * * @param type the key type for this map * @return a new, empty {@code EnumMap} */ public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) { return new EnumMap<K, V>(checkNotNull(type)); } /** * Creates an {@code EnumMap} with the same mappings as the specified map. * * @param map the map from which to initialize this {@code EnumMap} * @return a new {@code EnumMap} initialized with the mappings from {@code * map} * @throws IllegalArgumentException if {@code m} is not an {@code 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 {@code IdentityHashMap} instance. * * @return a new, empty {@code 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. * * <p>Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * * <p><b>Note:</b>If you only need to know whether two maps have the same * mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps */ @SuppressWarnings("unchecked") public static <K, V> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { if (left instanceof SortedMap) { SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left; SortedMapDifference<K, V> result = difference(sortedLeft, right); return result; } return difference(left, right, 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. * * <p>Values are compared using a provided equivalence, in the case of * equality, the value on the 'left' is returned in the difference. * * <p>Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @param valueEquivalence the equivalence relationship to use to compare * values * @return the difference between the two maps * @since 10.0 */ @Beta public static <K, V> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence) { Preconditions.checkNotNull(valueEquivalence); Map<K, V> onlyOnLeft = newHashMap(); Map<K, V> onlyOnRight = new HashMap<K, V>(right); // will whittle it down Map<K, V> onBoth = newHashMap(); Map<K, MapDifference.ValueDifference<V>> differences = newHashMap(); doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences); return new MapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences); } private static <K, V> void doDifference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) { for (Entry<? extends K, ? extends V> entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { V rightValue = onlyOnRight.remove(leftKey); if (valueEquivalence.equivalent(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { differences.put( leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { onlyOnLeft.put(leftKey, leftValue); } } } private static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) { if (map instanceof SortedMap) { return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map); } else { return Collections.unmodifiableMap(map); } } static class MapDifferenceImpl<K, V> implements MapDifference<K, V> { final Map<K, V> onlyOnLeft; final Map<K, V> onlyOnRight; final Map<K, V> onBoth; final Map<K, ValueDifference<V>> differences; MapDifferenceImpl(Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) { this.onlyOnLeft = unmodifiableMap(onlyOnLeft); this.onlyOnRight = unmodifiableMap(onlyOnRight); this.onBoth = unmodifiableMap(onBoth); this.differences = unmodifiableMap(differences); } @Override public boolean areEqual() { return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty(); } @Override public Map<K, V> entriesOnlyOnLeft() { return onlyOnLeft; } @Override public Map<K, V> entriesOnlyOnRight() { return onlyOnRight; } @Override public Map<K, V> entriesInCommon() { return onBoth; } @Override public Map<K, ValueDifference<V>> entriesDiffering() { return differences; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof MapDifference) { MapDifference<?, ?> other = (MapDifference<?, ?>) object; return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft()) && entriesOnlyOnRight().equals(other.entriesOnlyOnRight()) && entriesInCommon().equals(other.entriesInCommon()) && entriesDiffering().equals(other.entriesDiffering()); } return false; } @Override public int hashCode() { return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering()); } @Override public String toString() { if (areEqual()) { return "equal"; } StringBuilder result = new StringBuilder("not equal"); if (!onlyOnLeft.isEmpty()) { result.append(": only on left=").append(onlyOnLeft); } if (!onlyOnRight.isEmpty()) { result.append(": only on right=").append(onlyOnRight); } if (!differences.isEmpty()) { result.append(": value differences=").append(differences); } 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>(left, right); } private ValueDifferenceImpl(@Nullable V left, @Nullable V right) { this.left = left; this.right = right; } @Override public V leftValue() { return left; } @Override public V rightValue() { return right; } @Override public boolean equals(@Nullable Object object) { if (object instanceof MapDifference.ValueDifference) { MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object; return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(left, right); } @Override public String toString() { return "(" + left + ", " + right + ")"; } } /** * Computes the difference between two sorted maps, using the comparator of * the left map, or {@code 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. * * <p>Since this method uses {@code TreeMap} instances internally, the keys of * the right map must all compare as distinct according to the comparator * of the left map. * * <p><b>Note:</b>If you only need to know whether two sorted maps have the * same mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps * @since 11.0 */ public static <K, V> SortedMapDifference<K, V> difference( SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) { checkNotNull(left); checkNotNull(right); Comparator<? super K> comparator = orNaturalOrder(left.comparator()); SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator); SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator); onlyOnRight.putAll(right); // will whittle it down SortedMap<K, V> onBoth = Maps.newTreeMap(comparator); SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator); doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences); return new SortedMapDifferenceImpl<K, V>(onlyOnLeft, onlyOnRight, onBoth, differences); } static class SortedMapDifferenceImpl<K, V> extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> { SortedMapDifferenceImpl(SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) { super(onlyOnLeft, onlyOnRight, onBoth, differences); } @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 {@code * Ordering.natural()}. This method is an abomination of generics; the only * purpose of this method is to contain the ugly type-casting in one place. */ @SuppressWarnings("unchecked") static <E> Comparator<? super E> orNaturalOrder( @Nullable Comparator<? super E> comparator) { if (comparator != null) { // can't use ? : because of javac bug 5080917 return comparator; } return (Comparator<E>) Ordering.natural(); } /** * Returns a live {@link Map} view whose keys are the contents of {@code set} * and whose values are computed on demand using {@code function}. To get an * immutable <i>copy</i> instead, use {@link #toMap(Iterable, Function)}. * * <p>Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * * <p>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. * * <p><b>Warning</b>: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also * of type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta public static <K, V> Map<K, V> asMap( Set<K> set, Function<? super K, V> function) { if (set instanceof SortedSet) { return asMap((SortedSet<K>) set, function); } else { return new AsMapView<K, V>(set, function); } } /** * Returns a view of the sorted set as a map, mapping keys from the set * according to the specified function. * * <p>Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * * <p>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. * * <p><b>Warning</b>: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta public static <K, V> SortedMap<K, V> asMap( SortedSet<K> set, Function<? super K, V> function) { return Platform.mapsAsMapSortedSet(set, function); } static <K, V> SortedMap<K, V> asMapSortedIgnoreNavigable(SortedSet<K> set, Function<? super K, V> function) { return new SortedAsMapView<K, V>(set, function); } /** * Returns a view of the navigable set as a map, mapping keys from the set * according to the specified function. * * <p>Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * * <p>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. * * <p><b>Warning</b>: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also * of type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> asMap( NavigableSet<K> set, Function<? super K, V> function) { return new NavigableAsMapView<K, V>(set, function); } 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 set; } AsMapView(Set<K> set, Function<? super K, V> function) { this.set = checkNotNull(set); this.function = checkNotNull(function); } @Override public Set<K> createKeySet() { return removeOnlySet(backingSet()); } @Override Collection<V> createValues() { return Collections2.transform(set, function); } @Override public int size() { return backingSet().size(); } @Override public boolean containsKey(@Nullable Object key) { return backingSet().contains(key); } @Override public V get(@Nullable Object key) { if (Collections2.safeContains(backingSet(), key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public V remove(@Nullable Object key) { if (backingSet().remove(key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { backingSet().clear(); } @Override protected Set<Entry<K, V>> createEntrySet() { return new EntrySet<K, V>() { @Override Map<K, V> map() { return AsMapView.this; } @Override public Iterator<Entry<K, V>> iterator() { return asMapEntryIterator(backingSet(), function); } }; } } static <K, V> Iterator<Entry<K, V>> asMapEntryIterator( Set<K> set, final Function<? super K, V> function) { return new TransformedIterator<K, Entry<K,V>>(set.iterator()) { @Override Entry<K, V> transform(final K key) { return immutableEntry(key, function.apply(key)); } }; } private static class SortedAsMapView<K, V> extends AsMapView<K, V> implements SortedMap<K, V> { SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) { super(set, function); } @Override SortedSet<K> backingSet() { return (SortedSet<K>) super.backingSet(); } @Override public Comparator<? super K> comparator() { return backingSet().comparator(); } @Override public Set<K> keySet() { return removeOnlySortedSet(backingSet()); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return asMap(backingSet().subSet(fromKey, toKey), function); } @Override public SortedMap<K, V> headMap(K toKey) { return asMap(backingSet().headSet(toKey), function); } @Override public SortedMap<K, V> tailMap(K fromKey) { return asMap(backingSet().tailSet(fromKey), function); } @Override public K firstKey() { return backingSet().first(); } @Override public K lastKey() { return backingSet().last(); } } @GwtIncompatible("NavigableMap") private static final class NavigableAsMapView<K, V> extends AbstractNavigableMap<K, V> { /* * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the * NavigableMap methods. */ private final NavigableSet<K> set; private final Function<? super K, V> function; NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) { this.set = checkNotNull(ks); this.function = checkNotNull(vFunction); } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return asMap(set.headSet(toKey, inclusive), function); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return asMap(set.tailSet(fromKey, inclusive), function); } @Override public Comparator<? super K> comparator() { return set.comparator(); } @Override @Nullable public V get(@Nullable Object key) { if (Collections2.safeContains(set, key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { set.clear(); } @Override Iterator<Entry<K, V>> entryIterator() { return asMapEntryIterator(set, function); } @Override Iterator<Entry<K, V>> descendingEntryIterator() { return descendingMap().entrySet().iterator(); } @Override public NavigableSet<K> navigableKeySet() { return removeOnlyNavigableSet(set); } @Override public int size() { return set.size(); } @Override public NavigableMap<K, V> descendingMap() { return asMap(set.descendingSet(), function); } } private static <E> Set<E> removeOnlySet(final Set<E> set) { return new ForwardingSet<E>() { @Override protected Set<E> delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } }; } private static <E> SortedSet<E> removeOnlySortedSet(final SortedSet<E> set) { return new ForwardingSortedSet<E>() { @Override protected SortedSet<E> delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } @Override public SortedSet<E> headSet(E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return removeOnlySortedSet(super.subSet(fromElement, toElement)); } @Override public SortedSet<E> tailSet(E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } }; } @GwtIncompatible("NavigableSet") private static <E> NavigableSet<E> removeOnlyNavigableSet(final NavigableSet<E> set) { return new ForwardingNavigableSet<E>() { @Override protected NavigableSet<E> delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } @Override public SortedSet<E> headSet(E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return removeOnlySortedSet( super.subSet(fromElement, toElement)); } @Override public SortedSet<E> tailSet(E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return removeOnlyNavigableSet(super.subSet( fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet<E> descendingSet() { return removeOnlyNavigableSet(super.descendingSet()); } }; } /** * Returns an immutable map whose keys are the distinct elements of {@code * keys} and whose value for each key was computed by {@code valueFunction}. * The map's iteration order is the order of the first appearance of each key * in {@code keys}. * * <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of * a copy using {@link Maps#asMap(Set, Function)}. * * @throws NullPointerException if any element of {@code keys} is * {@code null}, or if {@code valueFunction} produces {@code null} * for any key * @since 14.0 */ @Beta public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys, Function<? super K, V> valueFunction) { return toMap(keys.iterator(), valueFunction); } /** * Returns an immutable map whose keys are the distinct elements of {@code * keys} and whose value for each key was computed by {@code valueFunction}. * The map's iteration order is the order of the first appearance of each key * in {@code keys}. * * @throws NullPointerException if any element of {@code keys} is * {@code null}, or if {@code valueFunction} produces {@code null} * for any key * @since 14.0 */ @Beta public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction) { checkNotNull(valueFunction); // Using LHM instead of a builder so as not to fail on duplicate keys Map<K, V> builder = newLinkedHashMap(); while (keys.hasNext()) { K key = keys.next(); builder.put(key, valueFunction.apply(key)); } return ImmutableMap.copyOf(builder); } /** * Returns an immutable map for which the {@link 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. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value */ public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterable<V> values, Function<? super V, K> keyFunction) { return uniqueIndex(values.iterator(), keyFunction); } /** * Returns an immutable map for which the {@link 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. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value * @since 10.0 */ public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterator<V> values, Function<? 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 {@code ImmutableMap<String, String>} from a {@code Properties} * instance. Properties normally derive from {@code Map<Object, Object>}, but * they typically contain strings, which is awkward. This method lets you get * a plain-old-{@code Map} out of a {@code Properties}. * * @param properties a {@code Properties} object to be converted * @return an immutable map containing all the entries in {@code properties} * @throws ClassCastException if any key in {@code Properties} is not a {@code * String} * @throws NullPointerException if any key or value in {@code Properties} is * null */ @GwtIncompatible("java.util.Properties") public static ImmutableMap<String, String> fromProperties( Properties properties) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); builder.put(key, properties.getProperty(key)); } return builder.build(); } /** * Returns an immutable map entry with the specified key and value. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * * <p>The returned entry is serializable. * * @param key the key to be associated with the returned entry * @param 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>(key, value); } /** * Returns an unmodifiable view of the specified set of entries. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}, * as do any operations that would modify the returned set. * * @param entrySet the entries for which to return an unmodifiable view * @return 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 {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * This also has the side-effect of redefining {@code equals} to comply with * the Entry contract, to avoid a possible nefarious implementation of equals. * * @param entry the entry for which to return an unmodifiable view * @return an unmodifiable view of the entry */ static <K, V> Entry<K, V> unmodifiableEntry(final Entry<? extends K, ? extends V> entry) { checkNotNull(entry); return new AbstractMapEntry<K, V>() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } }; } /** @see 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 = entries; } @Override protected Collection<Entry<K, V>> delegate() { return entries; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> delegate = super.iterator(); return new UnmodifiableIterator<Entry<K, V>>() { @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Entry<K, V> next() { return unmodifiableEntry(delegate.next()); } }; } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } } /** @see 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(this, object); } @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 <b>all</b> access * to the backing bimap is accomplished through the returned bimap. * * <p>It is imperative that the user manually synchronize on the returned map * when accessing any of its collection views: <pre> {@code * * 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()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap to be wrapped in a synchronized view * @return a sychronized view of the specified bimap */ public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) { return Synchronized.biMap(bimap, null); } /** * 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 {@code UnsupportedOperationException}. * * <p>The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap for which an unmodifiable view is to be returned * @return 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>(bimap, null); } /** @see 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) { unmodifiableMap = Collections.unmodifiableMap(delegate); this.delegate = delegate; this.inverse = inverse; } @Override protected Map<K, V> delegate() { return unmodifiableMap; } @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); } @Override public BiMap<V, K> inverse() { BiMap<V, K> result = inverse; return (result == null) ? inverse = new UnmodifiableBiMap<V, K>(delegate.inverse(), this) : result; } @Override public Set<V> values() { Set<V> result = values; return (result == null) ? values = Collections.unmodifiableSet(delegate.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: <pre> {@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);}</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code 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> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(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: <pre> {@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);}</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code 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> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(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: <pre> {@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);}</pre> * * ... prints {@code {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. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code 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> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a map whose values are derived from the original map's * entries. In contrast to {@link #transformValues}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@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);}</pre> * * ... prints {@code {verbose=verbose, sort=nosort}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code 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. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code 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>) fromMap, transformer); } return new TransformedEntriesMap<K, V1, V2>(fromMap, transformer); } /** * Returns a view of a sorted map whose values are derived from the original * sorted map's entries. In contrast to {@link #transformValues}, this * method's entry-transformation logic may depend on the key as well as the * value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@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);}</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code 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. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code 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(fromMap, transformer); } /** * Returns a view of a navigable map whose values are derived from the * original navigable map's entries. In contrast to {@link * #transformValues}, this method's entry-transformation logic may * depend on the key as well as the value. * * <p>All other properties of the transformed map, such as iteration order, * are left intact. For example, the code: <pre> {@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);}</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying map. * * <p>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. * * <p>The returned map is not thread-safe or serializable, even if the * underlying map is. * * <p>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 {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code 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. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code 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>(fromMap, transformer); } 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>(fromMap, transformer); } /** * 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 * {@link Maps#transformEntries(Map, EntryTransformer)}. * * @param <K> the key type of the input and output entries * @param <V1> the value type of the input entry * @param <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 * <i>generally expected</i>, but not absolutely required, to have the * following properties: * * <ul> * <li>Its execution does not cause any observable side effects. * <li>The computation is <i>consistent with equals</i>; that is, * {@link Objects#equal Objects.equal}{@code (k1, k2) &&} * {@link Objects#equal}{@code (v1, v2)} implies that {@code * Objects.equal(transformer.transform(k1, v1), * transformer.transform(k2, v2))}. * </ul> * * @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); } /** * Views a function as an entry transformer that ignores the entry key. */ 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); } }; } static <K, V1, V2> Function<V1, V2> asValueToValueFunction( final EntryTransformer<? super K, V1, V2> transformer, final K key) { checkNotNull(transformer); return new Function<V1, V2>() { @Override public V2 apply(@Nullable V1 v1) { return transformer.transformEntry(key, v1); } }; } /** * Views an entry transformer as a function from {@code Entry} to values. */ static <K, V1, V2> Function<Entry<K, V1>, V2> asEntryToValueFunction( final EntryTransformer<? super K, ? super V1, V2> transformer) { checkNotNull(transformer); return new Function<Entry<K, V1>, V2>() { @Override public V2 apply(Entry<K, V1> entry) { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; } /** * Returns a view of an entry transformed by the specified transformer. */ static <V2, K, V1> Entry<K, V2> transformEntry( final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) { checkNotNull(transformer); checkNotNull(entry); return new AbstractMapEntry<K, V2>() { @Override public K getKey() { return entry.getKey(); } @Override public V2 getValue() { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; } /** * Views an entry transformer as a function from entries to entries. */ static <K, V1, V2> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction( final EntryTransformer<? super K, ? super V1, V2> transformer) { checkNotNull(transformer); return new Function<Entry<K, V1>, Entry<K, V2>>() { @Override public Entry<K, V2> apply(final Entry<K, V1> entry) { return transformEntry(transformer, entry); } }; } static class TransformedEntriesMap<K, V1, V2> extends ImprovedAbstractMap<K, V2> { final Map<K, V1> fromMap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMap( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMap = checkNotNull(fromMap); this.transformer = checkNotNull(transformer); } @Override public int size() { return fromMap.size(); } @Override public boolean containsKey(Object key) { return fromMap.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 = fromMap.get(key); return (value != null || fromMap.containsKey(key)) ? transformer.transformEntry((K) key, value) : null; } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override public V2 remove(Object key) { return fromMap.containsKey(key) ? transformer.transformEntry((K) key, fromMap.remove(key)) : null; } @Override public void clear() { fromMap.clear(); } @Override public Set<K> keySet() { return fromMap.keySet(); } @Override protected Set<Entry<K, V2>> createEntrySet() { return new EntrySet<K, V2>() { @Override Map<K, V2> map() { return TransformedEntriesMap.this; } @Override public Iterator<Entry<K, V2>> iterator() { return Iterators.transform(fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); } }; } } static class TransformedEntriesSortedMap<K, V1, V2> extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> { protected SortedMap<K, V1> fromMap() { return (SortedMap<K, V1>) fromMap; } TransformedEntriesSortedMap(SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMap, transformer); } @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), transformer); } @Override public K lastKey() { return fromMap().lastKey(); } @Override public SortedMap<K, V2> subMap(K fromKey, K toKey) { return transformEntries( fromMap().subMap(fromKey, toKey), transformer); } @Override public SortedMap<K, V2> tailMap(K fromKey) { return transformEntries(fromMap().tailMap(fromKey), transformer); } } @GwtIncompatible("NavigableMap") private static class TransformedEntriesNavigableMap<K, V1, V2> extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> { TransformedEntriesNavigableMap(NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMap, transformer); } @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() { return transformEntries(fromMap().descendingMap(), transformer); } @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 public NavigableMap<K, V2> headMap(K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V2> headMap(K toKey, boolean inclusive) { return transformEntries( fromMap().headMap(toKey, inclusive), transformer); } @Override public Entry<K, V2> higherEntry(K key) { return transformEntry(fromMap().higherEntry(key)); } @Override public K higherKey(K key) { return fromMap().higherKey(key); } @Override public Entry<K, V2> lastEntry() { return transformEntry(fromMap().lastEntry()); } @Override public Entry<K, V2> lowerEntry(K key) { return transformEntry(fromMap().lowerEntry(key)); } @Override public K lowerKey(K key) { return fromMap().lowerKey(key); } @Override public NavigableSet<K> navigableKeySet() { return fromMap().navigableKeySet(); } @Override public Entry<K, V2> pollFirstEntry() { return transformEntry(fromMap().pollFirstEntry()); } @Override public Entry<K, V2> pollLastEntry() { return transformEntry(fromMap().pollLastEntry()); } @Override public NavigableMap<K, V2> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return transformEntries( fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); } @Override public NavigableMap<K, V2> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V2> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V2> tailMap(K fromKey, boolean inclusive) { return transformEntries( fromMap().tailMap(fromKey, inclusive), transformer); } @Nullable private Entry<K, V2> transformEntry(@Nullable Entry<K, V1> entry) { return (entry == null) ? null : Maps.transformEntry(transformer, entry); } @Override protected NavigableMap<K, V1> fromMap() { return (NavigableMap<K, V1>) super.fromMap(); } } static <K> Predicate<Entry<K, ?>> keyPredicateOnEntries(Predicate<? super K> keyPredicate) { return compose(keyPredicate, Maps.<K>keyFunction()); } static <V> Predicate<Entry<?, V>> valuePredicateOnEntries(Predicate<? super V> valuePredicate) { return compose(valuePredicate, Maps.<V>valueFunction()); } /** * Returns a map containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static <K, V> Map<K, V> filterKeys( Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof SortedMap) { return filterKeys((SortedMap<K, V>) unfiltered, keyPredicate); } else if (unfiltered instanceof BiMap) { return filterKeys((BiMap<K, V>) unfiltered, keyPredicate); } checkNotNull(keyPredicate); Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredKeyMap<K, V>( checkNotNull(unfiltered), keyPredicate, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ public static <K, V> SortedMap<K, V> filterKeys( SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate. * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the * bimap and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> * needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static <K, V> BiMap<K, V> filterKeys( BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { checkNotNull(keyPredicate); return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} whose values * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static <K, V> Map<K, V> filterValues( Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) { if (unfiltered instanceof SortedMap) { return filterValues((SortedMap<K, V>) unfiltered, valuePredicate); } else if (unfiltered instanceof BiMap) { return filterValues((BiMap<K, V>) unfiltered, valuePredicate); } return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ public static <K, V> SortedMap<K, V> filterValues( SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterValues( NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned bimap is a live view of {@code unfiltered}; changes to one affect the * other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the * bimap and its views. When given a value that doesn't satisfy the predicate, the bimap's * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the * predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> * needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static <K, V> BiMap<K, V> filterValues( BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} that satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes * to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. */ public static <K, V> Map<K, V> filterEntries( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { if (unfiltered instanceof SortedMap) { return filterEntries((SortedMap<K, V>) unfiltered, entryPredicate); } else if (unfiltered instanceof BiMap) { return filterEntries((BiMap<K, V>) unfiltered, entryPredicate); } checkNotNull(entryPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. * * @since 11.0 */ public static <K, V> SortedMap<K, V> filterEntries( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { return Platform.mapsFilterSortedMap(unfiltered, entryPredicate); } static <K, V> SortedMap<K, V> filterSortedIgnoreNavigable( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntrySortedMap) ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate) : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is <i>not</i> needed, it may be * faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with * equals</i>, as documented at {@link Predicate#apply}. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> filterEntries( NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryNavigableMap) ? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the bimap * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an * {@link IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} * method that throws an {@link IllegalArgumentException} when the existing key and the provided * value don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying bimap and determine which satisfy the filter. When a live * view is <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static <K, V> BiMap<K, V> filterEntries( BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(unfiltered); checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryBiMap) ? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered map. */ private static <K, V> Map<K, V> filterFiltered(AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { return new FilteredEntryMap<K, V>(map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate)); } private abstract static class AbstractFilteredMap<K, V> extends ImprovedAbstractMap<K, V> { final Map<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; AbstractFilteredMap( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } boolean apply(@Nullable Object key, @Nullable V value) { // This method is called only when the key is in the map, implying that // key is a K. @SuppressWarnings("unchecked") K k = (K) key; return predicate.apply(Maps.immutableEntry(k, value)); } @Override public V put(K key, V value) { checkArgument(apply(key, value)); return unfiltered.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { checkArgument(apply(entry.getKey(), entry.getValue())); } unfiltered.putAll(map); } @Override public boolean containsKey(Object key) { return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); } @Override public V get(Object key) { V value = unfiltered.get(key); return ((value != null) && apply(key, value)) ? value : null; } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public V remove(Object key) { return containsKey(key) ? unfiltered.remove(key) : null; } @Override Collection<V> createValues() { return new FilteredMapValues<K, V>(this, unfiltered, predicate); } } private static final class FilteredMapValues<K, V> extends Maps.Values<K, V> { Map<K, V> unfiltered; Predicate<? super Entry<K, V>> predicate; FilteredMapValues(Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { super(filteredMap); this.unfiltered = unfiltered; this.predicate = predicate; } @Override public boolean remove(Object o) { return Iterables.removeFirstMatching(unfiltered.entrySet(), Predicates.<Entry<K, V>>and(predicate, Maps.<V>valuePredicateOnEntries(equalTo(o)))) != null; } private boolean removeIf(Predicate<? super V> valuePredicate) { return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and( predicate, Maps.<V>valuePredicateOnEntries(valuePredicate))); } @Override public boolean removeAll(Collection<?> collection) { return removeIf(in(collection)); } @Override public boolean retainAll(Collection<?> collection) { return removeIf(not(in(collection))); } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } private static class FilteredKeyMap<K, V> extends AbstractFilteredMap<K, V> { Predicate<? super K> keyPredicate; FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); this.keyPredicate = keyPredicate; } @Override protected Set<Entry<K, V>> createEntrySet() { return Sets.filter(unfiltered.entrySet(), predicate); } @Override Set<K> createKeySet() { return Sets.filter(unfiltered.keySet(), keyPredicate); } // The cast is called only when the key is in the unfiltered map, implying // that key is a K. @Override @SuppressWarnings("unchecked") public boolean containsKey(Object key) { return unfiltered.containsKey(key) && keyPredicate.apply((K) key); } } static class FilteredEntryMap<K, V> extends AbstractFilteredMap<K, V> { /** * Entries in this set satisfy the predicate, but they don't validate the * input to {@code Entry.setValue()}. */ final Set<Entry<K, V>> filteredEntrySet; FilteredEntryMap( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); } @Override protected Set<Entry<K, V>> createEntrySet() { return new EntrySet(); } private class EntrySet extends ForwardingSet<Entry<K, V>> { @Override protected Set<Entry<K, V>> delegate() { return filteredEntrySet; } @Override public Iterator<Entry<K, V>> iterator() { return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) { @Override Entry<K, V> transform(final Entry<K, V> entry) { return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return entry; } @Override public V setValue(V newValue) { checkArgument(apply(getKey(), newValue)); return super.setValue(newValue); } }; } }; } } @Override Set<K> createKeySet() { return new KeySet(); } class KeySet extends Maps.KeySet<K, V> { KeySet() { super(FilteredEntryMap.this); } @Override public boolean remove(Object o) { if (containsKey(o)) { unfiltered.remove(o); return true; } return false; } private boolean removeIf(Predicate<? super K> keyPredicate) { return Iterables.removeIf(unfiltered.entrySet(), Predicates.<Entry<K, V>>and( predicate, Maps.<K>keyPredicateOnEntries(keyPredicate))); } @Override public boolean removeAll(Collection<?> c) { return removeIf(in(c)); } @Override public boolean retainAll(Collection<?> c) { return removeIf(not(in(c))); } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public <T> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered sorted map. */ private static <K, V> SortedMap<K, V> filterFiltered( FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntrySortedMap<K, V>(map.sortedMap(), predicate); } private static class FilteredEntrySortedMap<K, V> extends FilteredEntryMap<K, V> implements SortedMap<K, V> { FilteredEntrySortedMap(SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); } SortedMap<K, V> sortedMap() { return (SortedMap<K, V>) unfiltered; } @Override public SortedSet<K> keySet() { return (SortedSet<K>) super.keySet(); } @Override SortedSet<K> createKeySet() { return new SortedKeySet(); } class SortedKeySet extends KeySet implements SortedSet<K> { @Override public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override public SortedSet<K> subSet(K fromElement, K toElement) { return (SortedSet<K>) subMap(fromElement, toElement).keySet(); } @Override public SortedSet<K> headSet(K toElement) { return (SortedSet<K>) headMap(toElement).keySet(); } @Override public SortedSet<K> tailSet(K fromElement) { return (SortedSet<K>) tailMap(fromElement).keySet(); } @Override public K first() { return firstKey(); } @Override public K last() { return lastKey(); } } @Override public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override public K firstKey() { // correctly throws NoSuchElementException when filtered map is empty. return keySet().iterator().next(); } @Override public K lastKey() { SortedMap<K, V> headMap = sortedMap(); while (true) { // correctly throws NoSuchElementException when filtered map is empty. K key = headMap.lastKey(); if (apply(key, unfiltered.get(key))) { return key; } headMap = sortedMap().headMap(key); } } @Override public SortedMap<K, V> headMap(K toKey) { return new FilteredEntrySortedMap<K, V>(sortedMap().headMap(toKey), predicate); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return new FilteredEntrySortedMap<K, V>( sortedMap().subMap(fromKey, toKey), predicate); } @Override public SortedMap<K, V> tailMap(K fromKey) { return new FilteredEntrySortedMap<K, V>( sortedMap().tailMap(fromKey), predicate); } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered navigable map. */ @GwtIncompatible("NavigableMap") private static <K, V> NavigableMap<K, V> filterFiltered( FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.entryPredicate, entryPredicate); return new FilteredEntryNavigableMap<K, V>(map.unfiltered, predicate); } @GwtIncompatible("NavigableMap") private static class FilteredEntryNavigableMap<K, V> extends AbstractNavigableMap<K, V> { /* * It's less code to extend AbstractNavigableMap and forward the filtering logic to * FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap * methods. */ private final NavigableMap<K, V> unfiltered; private final Predicate<? super Entry<K, V>> entryPredicate; private final Map<K, V> filteredDelegate; FilteredEntryNavigableMap( NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { this.unfiltered = checkNotNull(unfiltered); this.entryPredicate = entryPredicate; this.filteredDelegate = new FilteredEntryMap<K, V>(unfiltered, entryPredicate); } @Override public Comparator<? super K> comparator() { return unfiltered.comparator(); } @Override public NavigableSet<K> navigableKeySet() { return new Maps.NavigableKeySet<K, V>(this) { @Override public boolean removeAll(Collection<?> c) { return Iterators.removeIf(unfiltered.entrySet().iterator(), Predicates.<Entry<K, V>>and(entryPredicate, Maps.<K>keyPredicateOnEntries(in(c)))); } @Override public boolean retainAll(Collection<?> c) { return Iterators.removeIf(unfiltered.entrySet().iterator(), Predicates.<Entry<K, V>>and( entryPredicate, Maps.<K>keyPredicateOnEntries(not(in(c))))); } }; } @Override public Collection<V> values() { return new FilteredMapValues<K, V>(this, unfiltered, entryPredicate); } @Override Iterator<Entry<K, V>> entryIterator() { return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate); } @Override Iterator<Entry<K, V>> descendingEntryIterator() { return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate); } @Override public int size() { return filteredDelegate.size(); } @Override @Nullable public V get(@Nullable Object key) { return filteredDelegate.get(key); } @Override public boolean containsKey(@Nullable Object key) { return filteredDelegate.containsKey(key); } @Override public V put(K key, V value) { return filteredDelegate.put(key, value); } @Override public V remove(@Nullable Object key) { return filteredDelegate.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { filteredDelegate.putAll(m); } @Override public void clear() { filteredDelegate.clear(); } @Override public Set<Entry<K, V>> entrySet() { return filteredDelegate.entrySet(); } @Override public Entry<K, V> pollFirstEntry() { return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate); } @Override public Entry<K, V> pollLastEntry() { return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate); } @Override public NavigableMap<K, V> descendingMap() { return filterEntries(unfiltered.descendingMap(), entryPredicate); } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return filterEntries( unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate); } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered map. */ private static <K, V> BiMap<K, V> filterFiltered( FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntryBiMap<K, V>(map.unfiltered(), predicate); } static final class FilteredEntryBiMap<K, V> extends FilteredEntryMap<K, V> implements BiMap<K, V> { private final BiMap<V, K> inverse; private static <K, V> Predicate<Entry<V, K>> inversePredicate( final Predicate<? super Entry<K, V>> forwardPredicate) { return new Predicate<Entry<V, K>>() { @Override public boolean apply(Entry<V, K> input) { return forwardPredicate.apply( Maps.immutableEntry(input.getValue(), input.getKey())); } }; } FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) { super(delegate, predicate); this.inverse = new FilteredEntryBiMap<V, K>( delegate.inverse(), inversePredicate(predicate), this); } private FilteredEntryBiMap( BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) { super(delegate, predicate); this.inverse = inverse; } BiMap<K, V> unfiltered() { return (BiMap<K, V>) unfiltered; } @Override public V forcePut(@Nullable K key, @Nullable V value) { checkArgument(apply(key, value)); return unfiltered().forcePut(key, value); } @Override public BiMap<V, K> inverse() { return inverse; } @Override public Set<V> values() { return inverse.keySet(); } } /** * Returns an unmodifiable view of the specified navigable map. Query operations on the returned * map read through to the specified map, and attempts to modify the returned map, whether direct * or via its views, result in an {@code UnsupportedOperationException}. * * <p>The returned navigable map will be serializable if the specified navigable map is * serializable. * * @param map the navigable map for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified navigable map * @since 12.0 */ @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, V> map) { checkNotNull(map); if (map instanceof UnmodifiableNavigableMap) { return map; } else { return new UnmodifiableNavigableMap<K, V>(map); } } @Nullable private static <K, V> Entry<K, V> unmodifiableOrNull(@Nullable Entry<K, V> entry) { return (entry == null) ? null : Maps.unmodifiableEntry(entry); } @GwtIncompatible("NavigableMap") static class UnmodifiableNavigableMap<K, V> extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable { private final NavigableMap<K, V> delegate; UnmodifiableNavigableMap(NavigableMap<K, V> delegate) { this.delegate = delegate; } UnmodifiableNavigableMap( NavigableMap<K, V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) { this.delegate = delegate; this.descendingMap = descendingMap; } @Override protected SortedMap<K, V> delegate() { return Collections.unmodifiableSortedMap(delegate); } @Override public Entry<K, V> lowerEntry(K key) { return unmodifiableOrNull(delegate.lowerEntry(key)); } @Override public K lowerKey(K key) { return delegate.lowerKey(key); } @Override public Entry<K, V> floorEntry(K key) { return unmodifiableOrNull(delegate.floorEntry(key)); } @Override public K floorKey(K key) { return delegate.floorKey(key); } @Override public Entry<K, V> ceilingEntry(K key) { return unmodifiableOrNull(delegate.ceilingEntry(key)); } @Override public K ceilingKey(K key) { return delegate.ceilingKey(key); } @Override public Entry<K, V> higherEntry(K key) { return unmodifiableOrNull(delegate.higherEntry(key)); } @Override public K higherKey(K key) { return delegate.higherKey(key); } @Override public Entry<K, V> firstEntry() { return unmodifiableOrNull(delegate.firstEntry()); } @Override public Entry<K, V> lastEntry() { return unmodifiableOrNull(delegate.lastEntry()); } @Override public final Entry<K, V> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public final Entry<K, V> pollLastEntry() { throw new UnsupportedOperationException(); } private transient UnmodifiableNavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { UnmodifiableNavigableMap<K, V> result = descendingMap; return (result == null) ? descendingMap = new UnmodifiableNavigableMap<K, V>(delegate.descendingMap(), this) : result; } @Override public Set<K> keySet() { return navigableKeySet(); } @Override public NavigableSet<K> navigableKeySet() { return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); } @Override public NavigableSet<K> descendingKeySet() { return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return Maps.unmodifiableNavigableMap(delegate.subMap( fromKey, fromInclusive, toKey, toInclusive)); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); } } /** * Returns a synchronized (thread-safe) navigable map backed by the specified * navigable map. In order to guarantee serial access, it is critical that * <b>all</b> access to the backing navigable map is accomplished * through the returned navigable map (or its views). * * <p>It is imperative that the user manually synchronize on the returned * navigable map when iterating over any of its collection views, or the * collections views of any of its {@code descendingMap}, {@code subMap}, * {@code headMap} or {@code tailMap} views. <pre> {@code * * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); * * // Needn't be in synchronized block * NavigableSet<K> set = map.navigableKeySet(); * * synchronized (map) { // Synchronizing on map, not set! * Iterator<K> it = set.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * }}</pre> * * <p>or: <pre> {@code * * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); * NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true); * * // Needn't be in synchronized block * NavigableSet<K> set2 = map2.descendingKeySet(); * * synchronized (map) { // Synchronizing on map, not map2 or set2! * Iterator<K> it = set2.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * }}</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param navigableMap the navigable map to be "wrapped" in a synchronized * navigable map. * @return a synchronized view of the specified navigable map. * @since 13.0 */ @GwtIncompatible("NavigableMap") public static <K, V> NavigableMap<K, V> synchronizedNavigableMap( NavigableMap<K, V> navigableMap) { return Synchronized.navigableMap(navigableMap); } /** * {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code * entrySet().isEmpty()} instead of {@code size() == 0} to speed up * implementations where {@code size()} is O(n), and it delegates the {@code * isEmpty()} methods of its key set and value collection to this * implementation. */ @GwtCompatible abstract static class ImprovedAbstractMap<K, V> extends AbstractMap<K, V> { /** * Creates the entry set to be returned by {@link #entrySet()}. This method * is invoked at most once on a given map, at the time when {@code entrySet} * is first called. */ abstract Set<Entry<K, V>> createEntrySet(); private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } Set<K> createKeySet() { return new KeySet<K, V>(this); } private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values<K, V>(this); } } /** * Delegates to {@link Map#get}. Returns {@code null} on {@code * ClassCastException} and {@code NullPointerException}. */ static <V> V safeGet(Map<?, V> map, @Nullable Object key) { checkNotNull(map); try { return map.get(key); } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } } /** * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code * ClassCastException} and {@code NullPointerException}. */ static boolean safeContainsKey(Map<?, ?> map, Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } /** * Delegates to {@link Map#remove}. Returns {@code null} on {@code * ClassCastException} and {@code NullPointerException}. */ static <V> V safeRemove(Map<?, V> map, Object key) { checkNotNull(map); try { return map.remove(key); } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } } /** * An admittedly inefficient implementation of {@link Map#containsKey}. */ static boolean containsKeyImpl(Map<?, ?> map, @Nullable Object key) { return Iterators.contains(keyIterator(map.entrySet().iterator()), key); } /** * An implementation of {@link Map#containsValue}. */ static boolean containsValueImpl(Map<?, ?> map, @Nullable Object value) { return Iterators.contains(valueIterator(map.entrySet().iterator()), value); } /** * Implements {@code Collection.contains} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * * <p>Note that {@code c} is the backing (delegate) collection, rather than * the forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object that might be contained in {@code c} * @return {@code true} if {@code c} contains {@code o} */ static <K, V> boolean containsEntryImpl(Collection<Entry<K, V>> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.contains(unmodifiableEntry((Entry<?, ?>) o)); } /** * Implements {@code Collection.remove} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * * <p>Note that {@code c} is backing (delegate) collection, rather than the * forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object to remove from {@code c} * @return {@code true} if {@code c} was changed */ static <K, V> boolean removeEntryImpl(Collection<Entry<K, V>> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.remove(unmodifiableEntry((Entry<?, ?>) o)); } /** * An implementation of {@link Map#equals}. */ static boolean equalsImpl(Map<?, ?> map, Object object) { if (map == object) { return true; } else if (object instanceof Map) { Map<?, ?> o = (Map<?, ?>) object; return map.entrySet().equals(o.entrySet()); } return false; } static final MapJoiner STANDARD_JOINER = Collections2.STANDARD_JOINER.withKeyValueSeparator("="); /** * An implementation of {@link Map#toString}. */ static String toStringImpl(Map<?, ?> map) { StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{'); STANDARD_JOINER.appendTo(sb, map); return sb.append('}').toString(); } /** * An implementation of {@link Map#putAll}. */ static <K, V> void putAllImpl( Map<K, V> self, Map<? extends K, ? extends V> map) { for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) { self.put(entry.getKey(), entry.getValue()); } } static class KeySet<K, V> extends Sets.ImprovedAbstractSet<K> { final Map<K, V> map; KeySet(Map<K, V> map) { this.map = checkNotNull(map); } Map<K, V> map() { return map; } @Override public Iterator<K> iterator() { return keyIterator(map().entrySet().iterator()); } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(Object o) { return map().containsKey(o); } @Override public boolean remove(Object o) { if (contains(o)) { map().remove(o); return true; } return false; } @Override public void clear() { map().clear(); } } @Nullable static <K> K keyOrNull(@Nullable Entry<K, ?> entry) { return (entry == null) ? null : entry.getKey(); } @Nullable static <V> V valueOrNull(@Nullable Entry<?, V> entry) { return (entry == null) ? null : entry.getValue(); } static class SortedKeySet<K, V> extends KeySet<K, V> implements SortedSet<K> { SortedKeySet(SortedMap<K, V> map) { super(map); } @Override SortedMap<K, V> map() { return (SortedMap<K, V>) super.map(); } @Override public Comparator<? super K> comparator() { return map().comparator(); } @Override public SortedSet<K> subSet(K fromElement, K toElement) { return new SortedKeySet<K, V>(map().subMap(fromElement, toElement)); } @Override public SortedSet<K> headSet(K toElement) { return new SortedKeySet<K, V>(map().headMap(toElement)); } @Override public SortedSet<K> tailSet(K fromElement) { return new SortedKeySet<K, V>(map().tailMap(fromElement)); } @Override public K first() { return map().firstKey(); } @Override public K last() { return map().lastKey(); } } @GwtIncompatible("NavigableMap") static class NavigableKeySet<K, V> extends SortedKeySet<K, V> implements NavigableSet<K> { NavigableKeySet(NavigableMap<K, V> map) { super(map); } @Override NavigableMap<K, V> map() { return (NavigableMap<K, V>) map; } @Override public K lower(K e) { return map().lowerKey(e); } @Override public K floor(K e) { return map().floorKey(e); } @Override public K ceiling(K e) { return map().ceilingKey(e); } @Override public K higher(K e) { return map().higherKey(e); } @Override public K pollFirst() { return keyOrNull(map().pollFirstEntry()); } @Override public K pollLast() { return keyOrNull(map().pollLastEntry()); } @Override public NavigableSet<K> descendingSet() { return map().descendingKeySet(); } @Override public Iterator<K> descendingIterator() { return descendingSet().iterator(); } @Override public NavigableSet<K> subSet( K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); } @Override public NavigableSet<K> headSet(K toElement, boolean inclusive) { return map().headMap(toElement, inclusive).navigableKeySet(); } @Override public NavigableSet<K> tailSet(K fromElement, boolean inclusive) { return map().tailMap(fromElement, inclusive).navigableKeySet(); } @Override public SortedSet<K> subSet(K fromElement, K toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet<K> headSet(K toElement) { return headSet(toElement, false); } @Override public SortedSet<K> tailSet(K fromElement) { return tailSet(fromElement, true); } } static class Values<K, V> extends AbstractCollection<V> { final Map<K, V> map; Values(Map<K, V> map) { this.map = checkNotNull(map); } final Map<K, V> map() { return map; } @Override public Iterator<V> iterator() { return valueIterator(map().entrySet().iterator()); } @Override public boolean remove(Object o) { try { return super.remove(o); } catch (UnsupportedOperationException e) { for (Entry<K, V> entry : map().entrySet()) { if (Objects.equal(o, entry.getValue())) { map().remove(entry.getKey()); return true; } } return false; } } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRemove = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRemove.add(entry.getKey()); } } return map().keySet().removeAll(toRemove); } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRetain = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRetain.add(entry.getKey()); } } return map().keySet().retainAll(toRetain); } } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(@Nullable Object o) { return map().containsValue(o); } @Override public void clear() { map().clear(); } } abstract static class EntrySet<K, V> extends Sets.ImprovedAbstractSet<Entry<K, V>> { abstract Map<K, V> map(); @Override public int size() { return map().size(); } @Override public void clear() { map().clear(); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; Object key = entry.getKey(); V value = Maps.safeGet(map(), key); return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); } return false; } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean remove(Object o) { if (contains(o)) { Entry<?, ?> entry = (Entry<?, ?>) o; return map().keySet().remove(entry.getKey()); } return false; } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove return Sets.removeAllImpl(this, c.iterator()); } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove Set<Object> keys = Sets.newHashSetWithExpectedSize(c.size()); for (Object o : c) { if (contains(o)) { Entry<?, ?> entry = (Entry<?, ?>) o; keys.add(entry.getKey()); } } return map().keySet().retainAll(keys); } } } @GwtIncompatible("NavigableMap") abstract static class DescendingMap<K, V> extends ForwardingMap<K, V> implements NavigableMap<K, V> { abstract NavigableMap<K, V> forward(); @Override protected final Map<K, V> delegate() { return forward(); } private transient Comparator<? super K> comparator; @SuppressWarnings("unchecked") @Override public Comparator<? super K> comparator() { Comparator<? super K> result = comparator; if (result == null) { Comparator<? super K> forwardCmp = forward().comparator(); if (forwardCmp == null) { forwardCmp = (Comparator) Ordering.natural(); } result = comparator = reverse(forwardCmp); } return result; } // If we inline this, we get a javac error. private static <T> Ordering<T> reverse(Comparator<T> forward) { return Ordering.from(forward).reverse(); } @Override public K firstKey() { return forward().lastKey(); } @Override public K lastKey() { return forward().firstKey(); } @Override public Entry<K, V> lowerEntry(K key) { return forward().higherEntry(key); } @Override public K lowerKey(K key) { return forward().higherKey(key); } @Override public Entry<K, V> floorEntry(K key) { return forward().ceilingEntry(key); } @Override public K floorKey(K key) { return forward().ceilingKey(key); } @Override public Entry<K, V> ceilingEntry(K key) { return forward().floorEntry(key); } @Override public K ceilingKey(K key) { return forward().floorKey(key); } @Override public Entry<K, V> higherEntry(K key) { return forward().lowerEntry(key); } @Override public K higherKey(K key) { return forward().lowerKey(key); } @Override public Entry<K, V> firstEntry() { return forward().lastEntry(); } @Override public Entry<K, V> lastEntry() { return forward().firstEntry(); } @Override public Entry<K, V> pollFirstEntry() { return forward().pollLastEntry(); } @Override public Entry<K, V> pollLastEntry() { return forward().pollFirstEntry(); } @Override public NavigableMap<K, V> descendingMap() { return forward(); } private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract Iterator<Entry<K, V>> entryIterator(); Set<Entry<K, V>> createEntrySet() { return new EntrySet<K, V>() { @Override Map<K, V> map() { return DescendingMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } }; } @Override public Set<K> keySet() { return navigableKeySet(); } private transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { NavigableSet<K> result = navigableKeySet; return (result == null) ? navigableKeySet = new NavigableKeySet<K, V>(this) : result; } @Override public NavigableSet<K> descendingKeySet() { return forward().navigableKeySet(); } @Override public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { return forward().tailMap(toKey, inclusive).descendingMap(); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { return forward().headMap(fromKey, inclusive).descendingMap(); } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public Collection<V> values() { return new Values<K, V>(this); } @Override public String toString() { return standardToString(); } } }
Java
/* * 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.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; /** An ordering that uses the natural order of the values. */ @GwtCompatible(serializable = true) @SuppressWarnings("unchecked") // TODO(kevinb): the right way to explain this?? final class NaturalOrdering extends Ordering<Comparable> implements Serializable { static final NaturalOrdering INSTANCE = new NaturalOrdering(); @Override public int compare(Comparable left, Comparable right) { checkNotNull(left); // for GWT checkNotNull(right); return left.compareTo(right); } @Override public <S extends Comparable> Ordering<S> reverse() { return (Ordering<S>) ReverseNaturalOrdering.INSTANCE; } // preserving singleton-ness gives equals()/hashCode() for free private Object readResolve() { return INSTANCE; } @Override public String toString() { return "Ordering.natural()"; } private NaturalOrdering() {} private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2012 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 java.util.Deque; import java.util.Iterator; /** * A deque which forwards all its method calls to another deque. Subclasses * should override one or more methods to modify the behavior of the backing * deque as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p><b>Warning:</b> The methods of {@code ForwardingDeque} forward * <b>indiscriminately</b> to the methods of the delegate. For example, * overriding {@link #add} alone <b>will not</b> change the behavior of {@link * #offer} which can lead to unexpected behavior. In this case, you should * override {@code offer} as well. * * @author Kurt Alfred Kluever * @since 12.0 */ public abstract class ForwardingDeque<E> extends ForwardingQueue<E> implements Deque<E> { /** Constructor for use by subclasses. */ protected ForwardingDeque() {} @Override protected abstract Deque<E> delegate(); @Override public void addFirst(E e) { delegate().addFirst(e); } @Override public void addLast(E e) { delegate().addLast(e); } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); } @Override public E getFirst() { return delegate().getFirst(); } @Override public E getLast() { return delegate().getLast(); } @Override public boolean offerFirst(E e) { return delegate().offerFirst(e); } @Override public boolean offerLast(E e) { return delegate().offerLast(e); } @Override public E peekFirst() { return delegate().peekFirst(); } @Override public E peekLast() { return delegate().peekLast(); } @Override public E pollFirst() { return delegate().pollFirst(); } @Override public E pollLast() { return delegate().pollLast(); } @Override public E pop() { return delegate().pop(); } @Override public void push(E e) { delegate().push(e); } @Override public E removeFirst() { return delegate().removeFirst(); } @Override public E removeLast() { return delegate().removeLast(); } @Override public boolean removeFirstOccurrence(Object o) { return delegate().removeFirstOccurrence(o); } @Override public boolean removeLastOccurrence(Object o) { return delegate().removeLastOccurrence(o); } }
Java
/* * 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.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Supplier; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import javax.annotation.Nullable; /** * Implementation of {@code Table} whose row keys and column keys are ordered * by their natural ordering or by supplied comparators. When constructing a * {@code TreeBasedTable}, you may provide comparators for the row keys and * the column keys, or you may use natural ordering for both. * * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and * {@link Map} specified by the {@link Table} interface. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link * #columnMap()} have iterators that don't support {@code remove()}. Otherwise, * all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code * column(columnKey).get(rowKey)} still runs quickly, since the row key is * provided. However, {@code column(columnKey).size()} takes longer, since an * iteration across all row keys occurs. * * <p>Because a {@code TreeBasedTable} has unique sorted values for a given * row, both {@code row(rowKey)} and {@code rowMap().get(rowKey)} are {@link * SortedMap} instances, instead of the {@link Map} specified in the {@link * Table} interface. * * <p>Note that this implementation is not synchronized. If multiple threads * access this table concurrently and one of the threads modifies the table, it * must be synchronized externally. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 7.0 */ @GwtCompatible(serializable = true) @Beta public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> { private final Comparator<? super C> columnComparator; private static class Factory<C, V> implements Supplier<TreeMap<C, V>>, Serializable { final Comparator<? super C> comparator; Factory(Comparator<? super C> comparator) { this.comparator = comparator; } @Override public TreeMap<C, V> get() { return new TreeMap<C, V>(comparator); } private static final long serialVersionUID = 0; } /** * Creates an empty {@code TreeBasedTable} that uses the natural orderings * of both row and column keys. * * <p>The method signature specifies {@code R extends Comparable} with a raw * {@link Comparable}, instead of {@code R extends Comparable<? super R>}, * and the same for {@code C}. That's necessary to support classes defined * without generics. */ public static <R extends Comparable, C extends Comparable, V> TreeBasedTable<R, C, V> create() { return new TreeBasedTable<R, C, V>(Ordering.natural(), Ordering.natural()); } /** * Creates an empty {@code TreeBasedTable} that is ordered by the specified * comparators. * * @param rowComparator the comparator that orders the row keys * @param columnComparator the comparator that orders the column keys */ public static <R, C, V> TreeBasedTable<R, C, V> create( Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { checkNotNull(rowComparator); checkNotNull(columnComparator); return new TreeBasedTable<R, C, V>(rowComparator, columnComparator); } /** * Creates a {@code TreeBasedTable} with the same mappings and sort order * as the specified {@code TreeBasedTable}. */ public static <R, C, V> TreeBasedTable<R, C, V> create( TreeBasedTable<R, C, ? extends V> table) { TreeBasedTable<R, C, V> result = new TreeBasedTable<R, C, V>( table.rowComparator(), table.columnComparator()); result.putAll(table); return result; } TreeBasedTable(Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { super(new TreeMap<R, Map<C, V>>(rowComparator), new Factory<C, V>(columnComparator)); this.columnComparator = columnComparator; } // TODO(jlevy): Move to StandardRowSortedTable? /** * Returns the comparator that orders the rows. With natural ordering, * {@link Ordering#natural()} is returned. */ public Comparator<? super R> rowComparator() { return rowKeySet().comparator(); } /** * Returns the comparator that orders the columns. With natural ordering, * {@link Ordering#natural()} is returned. */ public Comparator<? super C> columnComparator() { return columnComparator; } // TODO(user): make column return a SortedMap /** * {@inheritDoc} * * <p>Because a {@code TreeBasedTable} has unique sorted values for a given * row, this method returns a {@link SortedMap}, instead of the {@link Map} * specified in the {@link Table} interface. * @since 10.0 * (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 7.0) */ @Override public SortedMap<C, V> row(R rowKey) { return new TreeRow(rowKey); } private class TreeRow extends Row implements SortedMap<C, V> { @Nullable final C lowerBound; @Nullable final C upperBound; TreeRow(R rowKey) { this(rowKey, null, null); } TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) { super(rowKey); this.lowerBound = lowerBound; this.upperBound = upperBound; checkArgument(lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); } @Override public SortedSet<C> keySet() { return new Maps.SortedKeySet<C, V>(this); } @Override public Comparator<? super C> comparator() { return columnComparator(); } int compare(Object a, Object b) { // pretend we can compare anything @SuppressWarnings({"rawtypes", "unchecked"}) Comparator<Object> cmp = (Comparator) comparator(); return cmp.compare(a, b); } boolean rangeContains(@Nullable Object o) { return o != null && (lowerBound == null || compare(lowerBound, o) <= 0) && (upperBound == null || compare(upperBound, o) > 0); } @Override public SortedMap<C, V> subMap(C fromKey, C toKey) { checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); return new TreeRow(rowKey, fromKey, toKey); } @Override public SortedMap<C, V> headMap(C toKey) { checkArgument(rangeContains(checkNotNull(toKey))); return new TreeRow(rowKey, lowerBound, toKey); } @Override public SortedMap<C, V> tailMap(C fromKey) { checkArgument(rangeContains(checkNotNull(fromKey))); return new TreeRow(rowKey, fromKey, upperBound); } @Override public C firstKey() { SortedMap<C, V> backing = backingRowMap(); if (backing == null) { throw new NoSuchElementException(); } return backingRowMap().firstKey(); } @Override public C lastKey() { SortedMap<C, V> backing = backingRowMap(); if (backing == null) { throw new NoSuchElementException(); } return backingRowMap().lastKey(); } transient SortedMap<C, V> wholeRow; /* * If the row was previously empty, we check if there's a new row here every * time we're queried. */ SortedMap<C, V> wholeRow() { if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { wholeRow = (SortedMap<C, V>) backingMap.get(rowKey); } return wholeRow; } @Override SortedMap<C, V> backingRowMap() { return (SortedMap<C, V>) super.backingRowMap(); } @Override SortedMap<C, V> computeBackingRowMap() { SortedMap<C, V> map = wholeRow(); if (map != null) { if (lowerBound != null) { map = map.tailMap(lowerBound); } if (upperBound != null) { map = map.headMap(upperBound); } return map; } return null; } @Override void maintainEmptyInvariant() { if (wholeRow() != null && wholeRow.isEmpty()) { backingMap.remove(rowKey); wholeRow = null; backingRowMap = null; } } @Override public boolean containsKey(Object key) { return rangeContains(key) && super.containsKey(key); } @Override public V put(C key, V value) { checkArgument(rangeContains(checkNotNull(key))); return super.put(key, value); } } // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. @Override public SortedSet<R> rowKeySet() { return super.rowKeySet(); } @Override public SortedMap<R, Map<C, V>> rowMap() { return super.rowMap(); } /** * Overridden column iterator to return columns values in globally sorted * order. */ @Override Iterator<C> createColumnKeyIterator() { final Comparator<? super C> comparator = columnComparator(); final Iterator<C> merged = Iterators.mergeSorted(Iterables.transform(backingMap.values(), new Function<Map<C, V>, Iterator<C>>() { @Override public Iterator<C> apply(Map<C, V> input) { return input.keySet().iterator(); } }), comparator); return new AbstractIterator<C>() { C lastValue; @Override protected C computeNext() { while (merged.hasNext()) { C next = merged.next(); boolean duplicate = lastValue != null && comparator.compare(next, lastValue) == 0; // Keep looping till we find a non-duplicate value. if (!duplicate) { lastValue = next; return lastValue; } } lastValue = null; // clear reference to unused data return endOfData(); } }; } private static final long serialVersionUID = 0; }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.Nullable; /** * A collection that supports order-independent equality, like {@link Set}, but * may have duplicate elements. A multiset is also sometimes called a * <i>bag</i>. * * <p>Elements of a multiset that are equal to one another are referred to as * <i>occurrences</i> of the same single element. The total number of * occurrences of an element in a multiset is called the <i>count</i> of that * element (the terms "frequency" and "multiplicity" are equivalent, but not * used in this API). Since the count of an element is represented as an {@code * int}, a multiset may never contain more than {@link Integer#MAX_VALUE} * occurrences of any one element. * * <p>{@code Multiset} refines the specifications of several methods from * {@code Collection}. It also defines an additional query operation, {@link * #count}, which returns the count of an element. There are five new * bulk-modification operations, for example {@link #add(Object, int)}, to add * or remove multiple occurrences of an element at once, or to set the count of * an element to a specific value. These modification operations are optional, * but implementations which support the standard collection operations {@link * #add(Object)} or {@link #remove(Object)} are encouraged to implement the * related methods as well. Finally, two collection views are provided: {@link * #elementSet} contains the distinct elements of the multiset "with duplicates * collapsed", and {@link #entrySet} is similar but contains {@link Entry * Multiset.Entry} instances, each providing both a distinct element and the * count of that element. * * <p>In addition to these required methods, implementations of {@code * Multiset} are expected to provide two {@code static} creation methods: * {@code create()}, returning an empty multiset, and {@code * create(Iterable<? extends E>)}, returning a multiset containing the * given initial elements. This is simply a refinement of {@code Collection}'s * constructor recommendations, reflecting the new developments of Java 5. * * <p>As with other collection types, the modification operations are optional, * and should throw {@link UnsupportedOperationException} when they are not * implemented. Most implementations should support either all add operations * or none of them, all removal operations or none of them, and if and only if * all of these are supported, the {@code setCount} methods as well. * * <p>A multiset uses {@link Object#equals} to determine whether two instances * should be considered "the same," <i>unless specified otherwise</i> by the * implementation. * * <p>Common implementations include {@link ImmutableMultiset}, {@link * HashMultiset}, and {@link ConcurrentHashMultiset}. * * <p>If your values may be zero, negative, or outside the range of an int, you * may wish to use {@link com.google.common.util.concurrent.AtomicLongMap} * instead. Note, however, that unlike {@code Multiset}, {@code AtomicLongMap} * does not automatically remove zeros. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Multiset<E> extends Collection<E> { // Query Operations /** * Returns the number of occurrences of an element in this multiset (the * <i>count</i> of the element). Note that for an {@link Object#equals}-based * multiset, this gives the same result as {@link Collections#frequency} * (which would presumably perform more poorly). * * <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes * this operation; it correctly delegates to this method when dealing with a * multiset, but it can also accept any other iterable type. * * @param element the element to count occurrences of * @return the number of occurrences of the element in this multiset; possibly * zero but never negative */ int count(@Nullable Object element); // Bulk Operations /** * Adds a number of occurrences of an element to this multiset. Note that if * {@code occurrences == 1}, this method has the identical effect to {@link * #add(Object)}. This method is functionally equivalent (except in the case * of overflow) to the call {@code addAll(Collections.nCopies(element, * occurrences))}, which would presumably perform much more poorly. * * @param element the element to add occurrences of; may be null only if * explicitly allowed by the implementation * @param occurrences the number of occurrences of the element to add. May be * zero, in which case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if * this operation would result in more than {@link Integer#MAX_VALUE} * occurrences of the element * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements. Note that if {@code * occurrences} is zero, the implementation may opt to return normally. */ int add(@Nullable E element, int occurrences); /** * Removes a number of occurrences of the specified element from this * multiset. If the multiset contains fewer than this number of occurrences to * begin with, all occurrences will be removed. Note that if * {@code occurrences == 1}, this is functionally equivalent to the call * {@code remove(element)}. * * @param element the element to conditionally remove occurrences of * @param occurrences the number of occurrences of the element to remove. May * be zero, in which case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ int remove(@Nullable Object element, int occurrences); /** * Adds or removes the necessary occurrences of an element such that the * element attains the desired count. * * @param element the element to add or remove occurrences of; may be null * only if explicitly allowed by the implementation * @param count the desired count of the element in this multiset * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code count} is negative * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements. Note that if {@code * count} is zero, the implementor may optionally return zero instead. */ int setCount(E element, int count); /** * Conditionally sets the count of an element to a new value, as described in * {@link #setCount(Object, int)}, provided that the element has the expected * current count. If the current count is not {@code oldCount}, no change is * made. * * @param element the element to conditionally set the count of; may be null * only if explicitly allowed by the implementation * @param oldCount the expected present count of the element in this multiset * @param newCount the desired count of the element in this multiset * @return {@code true} if the condition for modification was met. This * implies that the multiset was indeed modified, unless * {@code oldCount == newCount}. * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is * negative * @throws NullPointerException if {@code element} is null and the * implementation does not permit null elements. Note that if {@code * oldCount} and {@code newCount} are both zero, the implementor may * optionally return {@code true} instead. */ boolean setCount(E element, int oldCount, int newCount); // Views /** * Returns the set of distinct elements contained in this multiset. The * element set is backed by the same data as the multiset, so any change to * either is immediately reflected in the other. The order of the elements in * the element set is unspecified. * * <p>If the element set supports any removal operations, these necessarily * cause <b>all</b> occurrences of the removed element(s) to be removed from * the multiset. Implementations are not expected to support the add * operations, although this is possible. * * <p>A common use for the element set is to find the number of distinct * elements in the multiset: {@code elementSet().size()}. * * @return a view of the set of distinct elements in this multiset */ Set<E> elementSet(); /** * Returns a view of the contents of this multiset, grouped into {@code * Multiset.Entry} instances, each providing an element of the multiset and * the count of that element. This set contains exactly one entry for each * distinct element in the multiset (thus it always has the same size as the * {@link #elementSet}). The order of the elements in the element set is * unspecified. * * <p>The entry set is backed by the same data as the multiset, so any change * to either is immediately reflected in the other. However, multiset changes * may or may not be reflected in any {@code Entry} instances already * retrieved from the entry set (this is implementation-dependent). * Furthermore, implementations are not required to support modifications to * the entry set at all, and the {@code Entry} instances themselves don't * even have methods for modification. See the specific implementation class * for more details on how its entry set handles modifications. * * @return a set of entries representing the data of this multiset */ Set<Entry<E>> entrySet(); /** * An unmodifiable element-count pair for a multiset. The {@link * Multiset#entrySet} method returns a view of the multiset whose elements * are of this class. A multiset implementation may return Entry instances * that are either live "read-through" views to the Multiset, or immutable * snapshots. Note that this type is unrelated to the similarly-named type * {@code Map.Entry}. * * @since 2.0 (imported from Google Collections Library) */ interface Entry<E> { /** * Returns the multiset element corresponding to this entry. Multiple calls * to this method always return the same instance. * * @return the element corresponding to this entry */ E getElement(); /** * Returns the count of the associated element in the underlying multiset. * This count may either be an unchanging snapshot of the count at the time * the entry was retrieved, or a live view of the current count of the * element in the multiset, depending on the implementation. Note that in * the former case, this method can never return zero, while in the latter, * it will return zero if all occurrences of the element were since removed * from the multiset. * * @return the count of the element; never negative */ int getCount(); /** * {@inheritDoc} * * <p>Returns {@code true} if the given object is also a multiset entry and * the two entries represent the same element and count. That is, two * entries {@code a} and {@code b} are equal if: <pre> {@code * * Objects.equal(a.getElement(), b.getElement()) * && a.getCount() == b.getCount()}</pre> */ @Override // TODO(kevinb): check this wrt TreeMultiset? boolean equals(Object o); /** * {@inheritDoc} * * <p>The hash code of a multiset entry for element {@code element} and * count {@code count} is defined as: <pre> {@code * * ((element == null) ? 0 : element.hashCode()) ^ count}</pre> */ @Override int hashCode(); /** * Returns the canonical string representation of this entry, defined as * follows. If the count for this entry is one, this is simply the string * representation of the corresponding element. Otherwise, it is the string * representation of the element, followed by the three characters {@code * " x "} (space, letter x, space), followed by the count. */ @Override String toString(); } // Comparison and hashing /** * Compares the specified object with this multiset for equality. Returns * {@code true} if the given object is also a multiset and contains equal * elements with equal counts, regardless of order. */ @Override // TODO(kevinb): caveats about equivalence-relation? boolean equals(@Nullable Object object); /** * Returns the hash code for this multiset. This is defined as the sum of * <pre> {@code * * ((element == null) ? 0 : element.hashCode()) ^ count(element)}</pre> * * <p>over all distinct elements in the multiset. It follows that a multiset and * its entry set always have the same hash code. */ @Override int hashCode(); /** * {@inheritDoc} * * <p>It is recommended, though not mandatory, that this method return the * result of invoking {@link #toString} on the {@link #entrySet}, yielding a * result such as {@code [a x 3, c, d x 2, e]}. */ @Override String toString(); // Refined Collection Methods /** * {@inheritDoc} * * <p>Elements that occur multiple times in the multiset will appear * multiple times in this iterator, though not necessarily sequentially. */ @Override Iterator<E> iterator(); /** * Determines whether this multiset contains the specified element. * * <p>This method refines {@link Collection#contains} to further specify that * it <b>may not</b> throw an exception in response to {@code element} being * null or of the wrong type. * * @param element the element to check for * @return {@code true} if this multiset contains at least one occurrence of * the element */ @Override boolean contains(@Nullable Object element); /** * Returns {@code true} if this multiset contains at least one occurrence of * each element in the specified collection. * * <p>This method refines {@link Collection#containsAll} to further specify * that it <b>may not</b> throw an exception in response to any of {@code * elements} being null or of the wrong type. * * <p><b>Note:</b> this method does not take into account the occurrence * count of an element in the two collections; it may still return {@code * true} even if {@code elements} contains several occurrences of an element * and this multiset contains only one. This is no different than any other * collection type like {@link List}, but it may be unexpected to the user of * a multiset. * * @param elements the collection of elements to be checked for containment in * this multiset * @return {@code true} if this multiset contains at least one occurrence of * each element contained in {@code elements} * @throws NullPointerException if {@code elements} is null */ @Override boolean containsAll(Collection<?> elements); /** * Adds a single occurrence of the specified element to this multiset. * * <p>This method refines {@link Collection#add}, which only <i>ensures</i> * the presence of the element, to further specify that a successful call must * always increment the count of the element, and the overall size of the * collection, by one. * * @param element the element to add one occurrence of; may be null only if * explicitly allowed by the implementation * @return {@code true} always, since this call is required to modify the * multiset, unlike other {@link Collection} types * @throws NullPointerException if {@code element} is null and this * implementation does not permit null elements * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences * of {@code element} are already contained in this multiset */ @Override boolean add(E element); /** * Removes a <i>single</i> occurrence of the specified element from this * multiset, if present. * * <p>This method refines {@link Collection#remove} to further specify that it * <b>may not</b> throw an exception in response to {@code element} being null * or of the wrong type. * * @param element the element to remove one occurrence of * @return {@code true} if an occurrence was found and removed */ @Override boolean remove(@Nullable Object element); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in * {@code c}, and only cares whether or not an element appears at all. * If you wish to remove one occurrence in this multiset for every occurrence * in {@code c}, see {@link Multisets#removeOccurrences(Multiset, Multiset)}. * * <p>This method refines {@link Collection#removeAll} to further specify that * it <b>may not</b> throw an exception in response to any of {@code elements} * being null or of the wrong type. */ @Override boolean removeAll(Collection<?> c); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in * {@code c}, and only cares whether or not an element appears at all. * If you wish to remove one occurrence in this multiset for every occurrence * in {@code c}, see {@link Multisets#retainOccurrences(Multiset, Multiset)}. * * <p>This method refines {@link Collection#retainAll} to further specify that * it <b>may not</b> throw an exception in response to any of {@code elements} * being null or of the wrong type. * * @see Multisets#retainOccurrences(Multiset, Multiset) */ @Override boolean retainAll(Collection<?> c); }
Java
/* * Copyright (C) 2009 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 com.google.common.primitives.Primitives; import java.util.Map; import javax.annotation.Nullable; /** * A class-to-instance map backed by an {@link ImmutableMap}. See also {@link * MutableClassToInstanceMap}. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ public final class ImmutableClassToInstanceMap<B> extends ForwardingMap<Class<? extends B>, B> implements ClassToInstanceMap<B> { /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <B> Builder<B> builder() { return new Builder<B>(); } /** * A builder for creating immutable class-to-instance maps. Example: * <pre> {@code * * static final ImmutableClassToInstanceMap<Handler> HANDLERS = * new ImmutableClassToInstanceMap.Builder<Handler>() * .put(FooHandler.class, new FooHandler()) * .put(BarHandler.class, new SubBarHandler()) * .put(Handler.class, new QuuxHandler()) * .build();}</pre> * * <p>After invoking {@link #build()} it is still possible to add more entries * and build again. Thus each map generated by this builder will be a superset * of any map generated before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<B> { private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder = ImmutableMap.builder(); /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public <T extends B> Builder<B> put(Class<T> key, T value) { mapBuilder.put(key, value); return this; } /** * Associates all of {@code map's} keys and values in the built map. * Duplicate keys are not allowed, and will cause {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null * @throws ClassCastException if any value is not an instance of the type * specified by its key */ public <T extends B> Builder<B> putAll( Map<? extends Class<? extends T>, ? extends T> map) { for (Entry<? extends Class<? extends T>, ? extends T> entry : map.entrySet()) { Class<? extends T> type = entry.getKey(); T value = entry.getValue(); mapBuilder.put(type, cast(type, value)); } return this; } private static <B, T extends B> T cast(Class<T> type, B value) { return Primitives.wrap(type).cast(value); } /** * Returns a new immutable class-to-instance map containing the entries * provided to this builder. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableClassToInstanceMap<B> build() { return new ImmutableClassToInstanceMap<B>(mapBuilder.build()); } } /** * Returns an immutable map containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p><b>Note:</b> Despite what the method name suggests, if {@code map} is * an {@code ImmutableClassToInstanceMap}, no copy will actually be performed. * * @throws NullPointerException if any key or value in {@code map} is null * @throws ClassCastException if any value is not an instance of the type * specified by its key */ public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf( Map<? extends Class<? extends S>, ? extends S> map) { if (map instanceof ImmutableClassToInstanceMap) { @SuppressWarnings("unchecked") // covariant casts safe (unmodifiable) // Eclipse won't compile if we cast to the parameterized type. ImmutableClassToInstanceMap<B> cast = (ImmutableClassToInstanceMap) map; return cast; } return new Builder<B>().putAll(map).build(); } private final ImmutableMap<Class<? extends B>, B> delegate; private ImmutableClassToInstanceMap( ImmutableMap<Class<? extends B>, B> delegate) { this.delegate = delegate; } @Override protected Map<Class<? extends B>, B> delegate() { return delegate; } @Override @SuppressWarnings("unchecked") // value could not get in if not a T @Nullable public <T extends B> T getInstance(Class<T> type) { return (T) delegate.get(checkNotNull(type)); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public <T extends B> T putInstance(Class<T> type, T value) { throw new UnsupportedOperationException(); } }
Java
/* * 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.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.lang.reflect.Array; import java.util.Collection; import javax.annotation.Nullable; /** * Static utility methods pertaining to object arrays. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class ObjectArrays { static final Object[] EMPTY_ARRAY = new Object[0]; private ObjectArrays() {} /** * Returns a new array of the given length with the specified component type. * * @param type the component type * @param length the length of the new array */ @GwtIncompatible("Array.newInstance(Class, int)") @SuppressWarnings("unchecked") public static <T> T[] newArray(Class<T> type, int length) { return (T[]) Array.newInstance(type, length); } /** * Returns a new array of the given length with the same type as a reference * array. * * @param reference any array of the desired type * @param length the length of the new array */ public static <T> T[] newArray(T[] reference, int length) { return Platform.newArray(reference, length); } /** * Returns a new array that contains the concatenated contents of two arrays. * * @param first the first array of elements to concatenate * @param second the second array of elements to concatenate * @param type the component type of the returned array */ @GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] concat(T[] first, T[] second, Class<T> type) { T[] result = newArray(type, first.length + second.length); System.arraycopy(first, 0, result, 0, first.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } /** * Returns a new array that prepends {@code element} to {@code array}. * * @param element the element to prepend to the front of {@code array} * @param array the array of elements to append * @return an array whose size is one larger than {@code array}, with * {@code element} occupying the first position, and the * elements of {@code array} occupying the remaining elements. */ public static <T> T[] concat(@Nullable T element, T[] array) { T[] result = newArray(array, array.length + 1); result[0] = element; System.arraycopy(array, 0, result, 1, array.length); return result; } /** * Returns a new array that appends {@code element} to {@code array}. * * @param array the array of elements to prepend * @param element the element to append to the end * @return an array whose size is one larger than {@code array}, with * the same contents as {@code array}, plus {@code element} occupying the * last position. */ public static <T> T[] concat(T[] array, @Nullable T element) { T[] result = arraysCopyOf(array, array.length + 1); result[array.length] = element; return result; } /** GWT safe version of Arrays.copyOf. */ static <T> T[] arraysCopyOf(T[] original, int newLength) { T[] copy = newArray(original, newLength); System.arraycopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Returns an array containing all of the elements in the specified * collection; the runtime type of the returned array is that of the specified * array. If the collection fits in the specified array, it is returned * therein. Otherwise, a new array is allocated with the runtime type of the * specified array and the size of the specified collection. * * <p>If the collection fits in the specified array with room to spare (i.e., * the array has more elements than the collection), the element in the array * immediately following the end of the collection is set to {@code null}. * This is useful in determining the length of the collection <i>only</i> if * the caller knows that the collection does not contain any null elements. * * <p>This method returns the elements in the order they are returned by the * collection's iterator. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements * @param array the array in which to place the collection elements * @throws ArrayStoreException if the runtime type of the specified array is * not a supertype of the runtime type of every element in the specified * collection */ static <T> T[] toArrayImpl(Collection<?> c, T[] array) { int size = c.size(); if (array.length < size) { array = newArray(array, size); } fillArray(c, array); if (array.length > size) { array[size] = null; } return array; } /** * Implementation of {@link Collection#toArray(Object[])} for collections backed by an object * array. the runtime type of the returned array is that of the specified array. If the collection * fits in the specified array, it is returned therein. Otherwise, a new array is allocated with * the runtime type of the specified array and the size of the specified collection. * * <p>If the collection fits in the specified array with room to spare (i.e., the array has more * elements than the collection), the element in the array immediately following the end of the * collection is set to {@code null}. This is useful in determining the length of the collection * <i>only</i> if the caller knows that the collection does not contain any null elements. */ static <T> T[] toArrayImpl(Object[] src, int offset, int len, T[] dst) { checkPositionIndexes(offset, offset + len, src.length); if (dst.length < len) { dst = newArray(dst, len); } else if (dst.length > len) { dst[len] = null; } System.arraycopy(src, offset, dst, 0, len); return dst; } /** * Returns an array containing all of the elements in the specified * collection. This method returns the elements in the order they are returned * by the collection's iterator. The returned array is "safe" in that no * references to it are maintained by the collection. The caller is thus free * to modify the returned array. * * <p>This method assumes that the collection size doesn't change while the * method is running. * * <p>TODO(kevinb): support concurrently modified collections? * * @param c the collection for which to return an array of elements */ static Object[] toArrayImpl(Collection<?> c) { return fillArray(c, new Object[c.size()]); } /** * Returns a copy of the specified subrange of the specified array that is literally an Object[], * and not e.g. a {@code String[]}. */ static Object[] copyAsObjectArray(Object[] elements, int offset, int length) { checkPositionIndexes(offset, offset + length, elements.length); if (length == 0) { return EMPTY_ARRAY; } Object[] result = new Object[length]; System.arraycopy(elements, offset, result, 0, length); return result; } private static Object[] fillArray(Iterable<?> elements, Object[] array) { int i = 0; for (Object element : elements) { array[i++] = element; } return array; } /** * Swaps {@code array[i]} with {@code array[j]}. */ static void swap(Object[] array, int i, int j) { Object temp = array[i]; array[i] = array[j]; array[j] = temp; } static Object[] checkElementsNotNull(Object... array) { return checkElementsNotNull(array, array.length); } static Object[] checkElementsNotNull(Object[] array, int length) { for (int i = 0; i < length; i++) { checkElementNotNull(array[i], i); } return array; } // We do this instead of Preconditions.checkNotNull to save boxing and array // creation cost. static Object checkElementNotNull(Object element, int index) { if (element == null) { throw new NullPointerException("at index " + index); } return element; } }
Java
/* * 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.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.collect.ObjectArrays.arraysCopyOf; import static com.google.common.collect.ObjectArrays.checkElementsNotNull; import com.google.common.annotations.GwtCompatible; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.RandomAccess; import javax.annotation.Nullable; /** * A high-performance, immutable, random-access {@code List} implementation. * Does not permit null elements. * * <p>Unlike {@link Collections#unmodifiableList}, which is a <i>view</i> of a * separate collection that can still change, an instance of {@code * ImmutableList} contains its own private data and will <i>never</i> change. * {@code ImmutableList} is convenient for {@code public static final} lists * ("constant lists") and also lets you easily make a "defensive copy" of a list * provided to your class by a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this type are * guaranteed to be immutable. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @see ImmutableMap * @see ImmutableSet * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableList<E> extends ImmutableCollection<E> implements List<E>, RandomAccess { private static final ImmutableList<Object> EMPTY = new RegularImmutableList<Object>(ObjectArrays.EMPTY_ARRAY); /** * Returns the empty immutable list. This set behaves and performs comparably * to {@link Collections#emptyList}, and is preferable mainly for consistency * and maintainability of your code. */ // Casting to any type is safe because the list will never hold any elements. @SuppressWarnings("unchecked") public static <E> ImmutableList<E> of() { return (ImmutableList<E>) EMPTY; } /** * Returns an immutable list containing a single element. This list behaves * and performs comparably to {@link Collections#singleton}, but will not * accept a null element. It is preferable mainly for consistency and * maintainability of your code. * * @throws NullPointerException if {@code element} is null */ public static <E> ImmutableList<E> of(E element) { return new SingletonImmutableList<E>(element); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2) { return construct(e1, e2); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3) { return construct(e1, e2, e3); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) { return construct(e1, e2, e3, e4); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) { return construct(e1, e2, e3, e4, e5); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) { return construct(e1, e2, e3, e4, e5, e6); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7) { return construct(e1, e2, e3, e4, e5, e6, e7); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) { return construct(e1, e2, e3, e4, e5, e6, e7, e8); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } // These go up to eleven. After that, you just get the varargs form, and // whatever warnings might come along with it. :( /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) { Object[] array = new Object[12 + others.length]; array[0] = e1; array[1] = e2; array[2] = e3; array[3] = e4; array[4] = e5; array[5] = e6; array[6] = e7; array[7] = e8; array[8] = e9; array[9] = e10; array[10] = e11; array[11] = e12; System.arraycopy(others, 0, array, 12, others.length); return construct(array); } /** * Returns an immutable list containing the given elements, in order. If * {@code elements} is a {@link Collection}, this method behaves exactly as * {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code * copyOf(elements.iterator()}. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) { checkNotNull(elements); // TODO(kevinb): is this here only for GWT? return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); } /** * Returns an immutable list containing the given elements, in order. * * <p>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. * * <p>Note that if {@code list} is a {@code List<String>}, then {@code * ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>} * containing each of the strings in {@code list}, while * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} * containing one element (the given list itself). * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) { if (elements instanceof ImmutableCollection) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList(); return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list; } return construct(elements.toArray()); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) { // We special-case for 0 or 1 elements, but going further is madness. if (!elements.hasNext()) { return of(); } E first = elements.next(); if (!elements.hasNext()) { return of(first); } else { return new ImmutableList.Builder<E>() .add(first) .addAll(elements) .build(); } } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E> ImmutableList<E> copyOf(E[] elements) { switch (elements.length) { case 0: return ImmutableList.of(); case 1: return new SingletonImmutableList<E>(elements[0]); default: return new RegularImmutableList<E>(checkElementsNotNull(elements.clone())); } } /** * Views the array as an immutable list. Checks for nulls; does not copy. */ private static <E> ImmutableList<E> construct(Object... elements) { return asImmutableList(checkElementsNotNull(elements)); } /** * Views the array as an immutable list. Does not check for nulls; does not copy. * * <p>The array must be internally created. */ static <E> ImmutableList<E> asImmutableList(Object[] elements) { return asImmutableList(elements, elements.length); } /** * Views the array as an immutable list. Copies if the specified range does not cover the complete * array. Does not check for nulls. */ static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) { switch (length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // collection had only Es in it ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]); return list; default: if (length < elements.length) { elements = arraysCopyOf(elements, length); } return new RegularImmutableList<E>(elements); } } ImmutableList() {} // This declaration is needed to make List.iterator() and // ImmutableCollection.iterator() consistent. @Override public UnmodifiableIterator<E> iterator() { return listIterator(); } @Override public UnmodifiableListIterator<E> listIterator() { return listIterator(0); } @Override public UnmodifiableListIterator<E> listIterator(int index) { return new AbstractIndexedListIterator<E>(size(), index) { @Override protected E get(int index) { return ImmutableList.this.get(index); } }; } @Override public int indexOf(@Nullable Object object) { return (object == null) ? -1 : Lists.indexOfImpl(this, object); } @Override public int lastIndexOf(@Nullable Object object) { return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object); } @Override public boolean contains(@Nullable Object object) { return indexOf(object) >= 0; } // constrain the return type to ImmutableList<E> /** * Returns an immutable list of the elements between the specified {@code * fromIndex}, inclusive, and {@code toIndex}, exclusive. (If {@code * fromIndex} and {@code toIndex} are equal, the empty immutable list is * returned.) */ @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, size()); int length = toIndex - fromIndex; switch (length) { case 0: return of(); case 1: return of(get(fromIndex)); default: return subListUnchecked(fromIndex, toIndex); } } /** * Called by the default implementation of {@link #subList} when {@code * toIndex - fromIndex > 1}, after index validation has already been * performed. */ ImmutableList<E> subListUnchecked(int fromIndex, int toIndex) { return new SubList(fromIndex, toIndex - fromIndex); } class SubList extends ImmutableList<E> { transient final int offset; transient final int length; SubList(int offset, int length) { this.offset = offset; this.length = length; } @Override public int size() { return length; } @Override public E get(int index) { checkElementIndex(index, length); return ImmutableList.this.get(index + offset); } @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, length); return ImmutableList.this.subList(fromIndex + offset, toIndex + offset); } @Override boolean isPartialView() { return true; } } /** * Guaranteed to throw an exception and leave the list unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final boolean addAll(int index, Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the list unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final E set(int index, E element) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the list unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void add(int index, E element) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the list unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final E remove(int index) { throw new UnsupportedOperationException(); } /** * Returns this list instance. * * @since 2.0 */ @Override public final ImmutableList<E> asList() { return this; } @Override int copyIntoArray(Object[] dst, int offset) { // this loop is faster for RandomAccess instances, which ImmutableLists are int size = size(); for (int i = 0; i < size; i++) { dst[offset + i] = get(i); } return offset + size; } /** * Returns a view of this immutable list in reverse order. For example, {@code * ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code * ImmutableList.of(3, 2, 1)}. * * @return a view of this immutable list in reverse order * @since 7.0 */ public ImmutableList<E> reverse() { return new ReverseImmutableList<E>(this); } private static class ReverseImmutableList<E> extends ImmutableList<E> { private final transient ImmutableList<E> forwardList; ReverseImmutableList(ImmutableList<E> backingList) { this.forwardList = backingList; } private int reverseIndex(int index) { return (size() - 1) - index; } private int reversePosition(int index) { return size() - index; } @Override public ImmutableList<E> reverse() { return forwardList; } @Override public boolean contains(@Nullable Object object) { return forwardList.contains(object); } @Override public int indexOf(@Nullable Object object) { int index = forwardList.lastIndexOf(object); return (index >= 0) ? reverseIndex(index) : -1; } @Override public int lastIndexOf(@Nullable Object object) { int index = forwardList.indexOf(object); return (index >= 0) ? reverseIndex(index) : -1; } @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, size()); return forwardList.subList( reversePosition(toIndex), reversePosition(fromIndex)).reverse(); } @Override public E get(int index) { checkElementIndex(index, size()); return forwardList.get(reverseIndex(index)); } @Override public int size() { return forwardList.size(); } @Override boolean isPartialView() { return forwardList.isPartialView(); } } @Override public boolean equals(@Nullable Object obj) { return Lists.equalsImpl(this, obj); } @Override public int hashCode() { int hashCode = 1; int n = size(); for (int i = 0; i < n; i++) { hashCode = 31 * hashCode + get(i).hashCode(); hashCode = ~~hashCode; // needed to deal with GWT integer overflow } return hashCode; } /* * Serializes ImmutableLists as their logical contents. This ensures that * implementation types do not leak into the serialized representation. */ static class SerializedForm implements Serializable { final Object[] elements; SerializedForm(Object[] elements) { this.elements = elements; } Object readResolve() { return copyOf(elements); } private static final long serialVersionUID = 0; } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } @Override Object writeReplace() { return new SerializedForm(toArray()); } /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <E> Builder<E> builder() { return new Builder<E>(); } /** * A builder for creating immutable list instances, especially {@code public * static final} lists ("constant lists"). Example: <pre> {@code * * public static final ImmutableList<Color> GOOGLE_COLORS * = new ImmutableList.Builder<Color>() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build();}</pre> * * <p>Builder instances can be reused; it is safe to call {@link #build} multiple * times to build multiple lists in series. Each new list contains all the * elements of the ones created before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<E> extends ImmutableCollection.ArrayBasedBuilder<E> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableList#builder}. */ public Builder() { this(DEFAULT_INITIAL_CAPACITY); } // TODO(user): consider exposing this Builder(int capacity) { super(capacity); } /** * Adds {@code element} to the {@code ImmutableList}. * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ @Override public Builder<E> add(E element) { super.add(element); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableList}. * * @param elements the {@code Iterable} to add to the {@code ImmutableList} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> addAll(Iterable<? extends E> elements) { super.addAll(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableList}. * * @param elements the {@code Iterable} to add to the {@code ImmutableList} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is null or contains a * null element */ @Override public Builder<E> add(E... elements) { super.add(elements); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableList}. * * @param elements the {@code Iterable} to add to the {@code ImmutableList} * @return this {@code Builder} object * @throws NullPointerException if {@code 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 {@code ImmutableList} based on the contents of * the {@code Builder}. */ @Override public ImmutableList<E> build() { return asImmutableList(contents, size); } } }
Java
/* * Copyright (C) 2010 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 com.google.common.annotations.GwtCompatible; import java.util.List; import javax.annotation.Nullable; /** * A list multimap which forwards all its method calls to another list multimap. * Subclasses should override one or more methods to modify the behavior of * the backing multimap as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 3.0 */ @GwtCompatible public abstract class ForwardingListMultimap<K, V> extends ForwardingMultimap<K, V> implements ListMultimap<K, V> { /** Constructor for use by subclasses. */ protected ForwardingListMultimap() {} @Override protected abstract ListMultimap<K, V> delegate(); @Override public List<V> get(@Nullable K key) { return delegate().get(key); } @Override public List<V> removeAll(@Nullable Object key) { return delegate().removeAll(key); } @Override public List<V> replaceValues(K key, Iterable<? extends V> values) { return delegate().replaceValues(key, values); } }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.annotation.Nullable; /** * An implementation of {@link ImmutableTable} holding an arbitrary number of * cells. * * @author Gregory Kick */ @GwtCompatible abstract class RegularImmutableTable<R, C, V> extends ImmutableTable<R, C, V> { RegularImmutableTable() {} abstract Cell<R, C, V> getCell(int iterationIndex); @Override final ImmutableSet<Cell<R, C, V>> createCellSet() { return isEmpty() ? ImmutableSet.<Cell<R, C, V>>of() : new CellSet(); } private final class CellSet extends ImmutableSet<Cell<R, C, V>> { @Override public int size() { return RegularImmutableTable.this.size(); } @Override public UnmodifiableIterator<Cell<R, C, V>> iterator() { return asList().iterator(); } @Override ImmutableList<Cell<R, C, V>> createAsList() { return new ImmutableAsList<Cell<R, C, V>>() { @Override public Cell<R, C, V> get(int index) { return getCell(index); } @Override ImmutableCollection<Cell<R, C, V>> delegateCollection() { return CellSet.this; } }; } @Override public boolean contains(@Nullable Object object) { if (object instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) object; Object value = get(cell.getRowKey(), cell.getColumnKey()); return value != null && value.equals(cell.getValue()); } return false; } @Override boolean isPartialView() { return false; } } abstract V getValue(int iterationIndex); @Override final ImmutableCollection<V> createValues() { return isEmpty() ? ImmutableList.<V>of() : new Values(); } private final class Values extends ImmutableList<V> { @Override public int size() { return RegularImmutableTable.this.size(); } @Override public V get(int index) { return getValue(index); } @Override boolean isPartialView() { return true; } } static <R, C, V> RegularImmutableTable<R, C, V> forCells( List<Cell<R, C, V>> cells, @Nullable final Comparator<? super R> rowComparator, @Nullable final Comparator<? super C> columnComparator) { checkNotNull(cells); if (rowComparator != null || columnComparator != null) { /* * This sorting logic leads to a cellSet() ordering that may not be expected and that isn't * documented in the Javadoc. If a row Comparator is provided, cellSet() iterates across the * columns in the first row, the columns in the second row, etc. If a column Comparator is * provided but a row Comparator isn't, cellSet() iterates across the rows in the first * column, the rows in the second column, etc. */ Comparator<Cell<R, C, V>> comparator = new Comparator<Cell<R, C, V>>() { @Override public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) { int rowCompare = (rowComparator == null) ? 0 : rowComparator.compare(cell1.getRowKey(), cell2.getRowKey()); if (rowCompare != 0) { return rowCompare; } return (columnComparator == null) ? 0 : columnComparator.compare(cell1.getColumnKey(), cell2.getColumnKey()); } }; Collections.sort(cells, comparator); } return forCellsInternal(cells, rowComparator, columnComparator); } static <R, C, V> RegularImmutableTable<R, C, V> forCells( Iterable<Cell<R, C, V>> cells) { return forCellsInternal(cells, null, null); } /** * A factory that chooses the most space-efficient representation of the * table. */ private static final <R, C, V> RegularImmutableTable<R, C, V> forCellsInternal(Iterable<Cell<R, C, V>> cells, @Nullable Comparator<? super R> rowComparator, @Nullable Comparator<? super C> columnComparator) { ImmutableSet.Builder<R> rowSpaceBuilder = ImmutableSet.builder(); ImmutableSet.Builder<C> columnSpaceBuilder = ImmutableSet.builder(); ImmutableList<Cell<R, C, V>> cellList = ImmutableList.copyOf(cells); for (Cell<R, C, V> cell : cellList) { rowSpaceBuilder.add(cell.getRowKey()); columnSpaceBuilder.add(cell.getColumnKey()); } ImmutableSet<R> rowSpace = rowSpaceBuilder.build(); if (rowComparator != null) { List<R> rowList = Lists.newArrayList(rowSpace); Collections.sort(rowList, rowComparator); rowSpace = ImmutableSet.copyOf(rowList); } ImmutableSet<C> columnSpace = columnSpaceBuilder.build(); if (columnComparator != null) { List<C> columnList = Lists.newArrayList(columnSpace); Collections.sort(columnList, columnComparator); columnSpace = ImmutableSet.copyOf(columnList); } // use a dense table if more than half of the cells have values // TODO(gak): tune this condition based on empirical evidence return (cellList.size() > (((long) rowSpace.size() * columnSpace.size()) / 2)) ? new DenseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace) : new SparseImmutableTable<R, C, V>(cellList, rowSpace, columnSpace); } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; /** * A supertype for filtered {@link SetMultimap} implementations. * * @author Louis Wasserman */ @GwtCompatible interface FilteredSetMultimap<K, V> extends FilteredMultimap<K, V>, SetMultimap<K, V> { @Override SetMultimap<K, V> unfiltered(); }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Predicate; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some * {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not * possible to <i>iterate</i> over these contained values. To do so, pass this range instance and * an appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}. * * <h3>Types of ranges</h3> * * <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated * <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the * endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each * side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket * ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means * it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all * <i>x</i> such that <i>statement</i>.") * * <blockquote><table> * <tr><td><b>Notation</b> <td><b>Definition</b> <td><b>Factory method</b> * <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open} * <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed} * <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed} * <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen} * <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan} * <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast} * <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan} * <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost} * <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all} * </table></blockquote> * * <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints * may be equal only if at least one of the bounds is closed: * * <ul> * <li>{@code [a..a]} : a singleton range * <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid * <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown * </ul> * * <h3>Warnings</h3> * * <ul> * <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do * not</b> allow the endpoint instances to mutate after the range is created! * <li>Your value type's comparison method should be {@linkplain Comparable consistent with equals} * if at all possible. Otherwise, be aware that concepts used throughout this documentation such * as "equal", "same", "unique" and so on actually refer to whether {@link Comparable#compareTo * compareTo} returns zero, not whether {@link Object#equals equals} returns {@code true}. * <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause * undefined horrible things to happen in {@code Range}. For now, the Range API does not prevent * its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. <b>This * may change in the future.</b> * </ul> * * <h3>Other notes</h3> * * <ul> * <li>Instances of this type are obtained using the static factory methods in this class. * <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them must * also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C}, {@code * r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a {@code * Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from 1 to * 100." * <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link * #contains}. * <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property * <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}. * Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having * property <i>P</i>. See, for example, the definition of {@link #intersection intersection}. * </ul> * * <h3>Further reading</h3> * * <p>See the Guava User Guide article on * <a href="http://code.google.com/p/guava-libraries/wiki/RangesExplained">{@code Range}</a>. * * @author Kevin Bourrillion * @author Gregory Kick * @since 10.0 */ @GwtCompatible @SuppressWarnings("rawtypes") public final class Range<C extends Comparable> implements Predicate<C>, Serializable { private static final Function<Range, Cut> LOWER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.lowerBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> lowerBoundFn() { return (Function) LOWER_BOUND_FN; } private static final Function<Range, Cut> UPPER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.upperBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> upperBoundFn() { return (Function) UPPER_BOUND_FN; } static final Ordering<Range<?>> RANGE_LEX_ORDERING = new Ordering<Range<?>>() { @Override public int compare(Range<?> left, Range<?> right) { return ComparisonChain.start() .compare(left.lowerBound, right.lowerBound) .compare(left.upperBound, right.upperBound) .result(); } }; static <C extends Comparable<?>> Range<C> create( Cut<C> lowerBound, Cut<C> upperBound) { return new Range<C>(lowerBound, upperBound); } /** * Returns a range that contains all values strictly greater than {@code * lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than <i>or * equal to</i> {@code upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> open(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) { return create(Cut.belowValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closedOpen( C lower, C upper) { return create(Cut.belowValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values strictly greater than {@code * lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> openClosed( C lower, C upper) { return create(Cut.aboveValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains any value from {@code lower} to {@code * upper}, where each endpoint may be either inclusive (closed) or exclusive * (open). * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> range( C lower, BoundType lowerType, C upper, BoundType upperType) { checkNotNull(lowerType); checkNotNull(upperType); Cut<C> lowerBound = (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower); Cut<C> upperBound = (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper); return create(lowerBound, upperBound); } /** * Returns a range that contains all values strictly less than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) { return create(Cut.<C>belowAll(), Cut.belowValue(endpoint)); } /** * Returns a range that contains all values less than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atMost(C endpoint) { return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint)); } /** * Returns a range with no lower bound up to the given endpoint, which may be * either inclusive (closed) or exclusive (open). * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> upTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return lessThan(endpoint); case CLOSED: return atMost(endpoint); default: throw new AssertionError(); } } /** * Returns a range that contains all values strictly greater than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) { return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range that contains all values greater than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) { return create(Cut.belowValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range from the given endpoint, which may be either inclusive * (closed) or exclusive (open), with no upper bound. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> downTo( C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return greaterThan(endpoint); case CLOSED: return atLeast(endpoint); default: throw new AssertionError(); } } private static final Range<Comparable> ALL = new Range<Comparable>(Cut.belowAll(), Cut.aboveAll()); /** * Returns a range that contains every value of type {@code C}. * * @since 14.0 */ @SuppressWarnings("unchecked") public static <C extends Comparable<?>> Range<C> all() { return (Range) ALL; } /** * Returns a range that {@linkplain Range#contains(Comparable) contains} only * the given value. The returned range is {@linkplain BoundType#CLOSED closed} * on both ends. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> singleton(C value) { return closed(value, value); } /** * Returns the minimal range that * {@linkplain Range#contains(Comparable) contains} all of the given values. * The returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> * @throws NoSuchElementException if {@code values} is empty * @throws NullPointerException if any of {@code values} is null * @since 14.0 */ public static <C extends Comparable<?>> Range<C> encloseAll( Iterable<C> values) { checkNotNull(values); if (values instanceof ContiguousSet) { return ((ContiguousSet<C>) values).range(); } Iterator<C> valueIterator = values.iterator(); C min = checkNotNull(valueIterator.next()); C max = min; while (valueIterator.hasNext()) { C value = checkNotNull(valueIterator.next()); min = Ordering.natural().min(min, value); max = Ordering.natural().max(max, value); } return closed(min, max); } final Cut<C> lowerBound; final Cut<C> upperBound; private Range(Cut<C> lowerBound, Cut<C> upperBound) { if (lowerBound.compareTo(upperBound) > 0 || lowerBound == Cut.<C>aboveAll() || upperBound == Cut.<C>belowAll()) { throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound)); } this.lowerBound = checkNotNull(lowerBound); this.upperBound = checkNotNull(upperBound); } /** * Returns {@code true} if this range has a lower endpoint. */ public boolean hasLowerBound() { return lowerBound != Cut.belowAll(); } /** * Returns the lower endpoint of this range. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public C lowerEndpoint() { return lowerBound.endpoint(); } /** * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes * its lower endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public BoundType lowerBoundType() { return lowerBound.typeAsLowerBound(); } /** * Returns {@code true} if this range has an upper endpoint. */ public boolean hasUpperBound() { return upperBound != Cut.aboveAll(); } /** * Returns the upper endpoint of this range. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public C upperEndpoint() { return upperBound.endpoint(); } /** * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes * its upper endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public BoundType upperBoundType() { return upperBound.typeAsUpperBound(); } /** * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and * can't be constructed at all.) * * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b> * considered empty, even though they contain no actual values. In these cases, it may be * helpful to preprocess ranges with {@link #canonical(DiscreteDomain)}. */ public boolean isEmpty() { return lowerBound.equals(upperBound); } /** * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)} * returns {@code false}. */ public boolean contains(C value) { checkNotNull(value); // let this throw CCE if there is some trickery going on return lowerBound.isLessThan(value) && !upperBound.isLessThan(value); } /** * Equivalent to {@link #contains}; provided only to satisfy the {@link Predicate} interface. When * using a reference of type {@code Range}, always invoke {@link #contains} directly instead. */ @Override public boolean apply(C input) { return contains(input); } /** * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in * this range. */ public boolean containsAll(Iterable<? extends C> values) { if (Iterables.isEmpty(values)) { return true; } // this optimizes testing equality of two range-backed sets if (values instanceof SortedSet) { SortedSet<? extends C> set = cast(values); Comparator<?> comparator = set.comparator(); if (Ordering.natural().equals(comparator) || comparator == null) { return contains(set.first()) && contains(set.last()); } } for (C value : values) { if (!contains(value)) { return false; } } return true; } /** * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this * range. Examples: * * <ul> * <li>{@code [3..6]} encloses {@code [4..5]} * <li>{@code (3..6)} encloses {@code (3..6)} * <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty) * <li>{@code (3..6]} does not enclose {@code [3..6]} * <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value * contained by the latter range) * <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value * contained by the latter range) * </ul> * * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies * {@code a.contains(v)}, but as the last two examples illustrate, the converse is not always * true. * * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure * also implies {@linkplain #isConnected connectedness}. */ public boolean encloses(Range<C> other) { return lowerBound.compareTo(other.lowerBound) <= 0 && upperBound.compareTo(other.upperBound) >= 0; } /** * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses * enclosed} by both this range and {@code other}. * * <p>For example, * <ul> * <li>{@code [2, 4)} and {@code [5, 7)} are not connected * <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)} * <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range * {@code [4, 4)} * </ul> * * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this * method returns {@code true}. * * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain * Equivalence equivalence relation} as it is not transitive. * * <p>Note that certain discrete ranges are not considered connected, even though there are no * elements "between them." For example, {@code [3, 5]} is not considered connected to {@code * [6, 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with * {@link #canonical(DiscreteDomain)} before testing for connectedness. */ public boolean isConnected(Range<C> other) { return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; } /** * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code * connectedRange}, if such a range exists. * * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)} * yields the empty range {@code [5..5)}. * * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected * connected}. * * <p>The intersection operation is commutative, associative and idempotent, and its identity * element is {@link Range#all}). * * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false} */ public Range<C> intersection(Range<C> connectedRange) { int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound); int upperCmp = upperBound.compareTo(connectedRange.upperBound); if (lowerCmp >= 0 && upperCmp <= 0) { return this; } else if (lowerCmp <= 0 && upperCmp >= 0) { return connectedRange; } else { Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound; Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound; return create(newLower, newUpper); } } /** * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}. * * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can * also be called their <i>union</i>. If they are not, note that the span might contain values * that are not contained in either input range. * * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative * and idempotent. Unlike it, it is always well-defined for any two input ranges. */ public Range<C> span(Range<C> other) { int lowerCmp = lowerBound.compareTo(other.lowerBound); int upperCmp = upperBound.compareTo(other.upperBound); if (lowerCmp <= 0 && upperCmp >= 0) { return this; } else if (lowerCmp >= 0 && upperCmp <= 0) { return other; } else { Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound; Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound; return create(newLower, newUpper); } } /** * Returns an {@link ContiguousSet} containing the same values in the given domain * {@linkplain Range#contains contained} by this range. * * <p><b>Note:</b> {@code a.asSet(d).equals(b.asSet(d))} does not imply {@code a.equals(b)}! For * example, {@code a} and {@code b} could be {@code [2..4]} and {@code (1..5)}, or the empty * ranges {@code [3..3)} and {@code [4..4)}. * * <p><b>Warning:</b> Be extremely careful what you do with the {@code asSet} view of a large * range (such as {@code Range.greaterThan(0)}). Certain operations on such a set can be * performed efficiently, but others (such as {@link Set#hashCode} or {@link * Collections#frequency}) can cause major performance problems. * * <p>The returned set's {@link Object#toString} method returns a short-hand form of the set's * contents, such as {@code "[1..100]}"}. * * @throws IllegalArgumentException if neither this range nor the domain has a lower bound, or if * neither has an upper bound * @deprecated Use {@code ContiguousSet.create(range, domain)}. To be removed in Guava 16.0. */ @Beta @GwtCompatible(serializable = false) @Deprecated public ContiguousSet<C> asSet(DiscreteDomain<C> domain) { return ContiguousSet.create(this, domain); } /** * Returns the canonical form of this range in the given domain. The canonical form has the * following properties: * * <ul> * <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in other * words, {@code ContiguousSet.create(a.canonical(domain), domain).equals( * ContiguousSet.create(a, domain))} * <li>uniqueness: unless {@code a.isEmpty()}, * {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} implies * {@code a.canonical(domain).equals(b.canonical(domain))} * <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} * </ul> * * <p>Furthermore, this method guarantees that the range returned will be one of the following * canonical forms: * * <ul> * <li>[start..end) * <li>[start..+∞) * <li>(-∞..end) (only if type {@code C} is unbounded below) * <li>(-∞..+∞) (only if type {@code C} is unbounded below) * </ul> */ public Range<C> canonical(DiscreteDomain<C> domain) { checkNotNull(domain); Cut<C> lower = lowerBound.canonical(domain); Cut<C> upper = upperBound.canonical(domain); return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); } /** * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b> * equal to one another, despite the fact that they each contain precisely the same set of values. * Similarly, empty ranges are not equal unless they have exactly the same representation, so * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal. */ @Override public boolean equals(@Nullable Object object) { if (object instanceof Range) { Range<?> other = (Range<?>) object; return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); } return false; } /** Returns a hash code for this range. */ @Override public int hashCode() { return lowerBound.hashCode() * 31 + upperBound.hashCode(); } /** * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are * listed in the class documentation). */ @Override public String toString() { return toString(lowerBound, upperBound); } private static String toString(Cut<?> lowerBound, Cut<?> upperBound) { StringBuilder sb = new StringBuilder(16); lowerBound.describeAsLowerBound(sb); sb.append('\u2025'); upperBound.describeAsUpperBound(sb); return sb.toString(); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ private static <T> SortedSet<T> cast(Iterable<T> iterable) { return (SortedSet<T>) iterable; } Object readResolve() { if (this.equals(ALL)) { return all(); } else { return this; } } @SuppressWarnings("unchecked") // this method may throw CCE static int compareOrThrow(Comparable left, Comparable right) { return left.compareTo(right); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Preconditions; import java.util.List; import javax.annotation.Nullable; /** * Implementation of {@link ImmutableList} with exactly one element. * * @author Hayward Chan */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // uses writeReplace(), not default serialization final class SingletonImmutableList<E> extends ImmutableList<E> { final transient E element; SingletonImmutableList(E element) { this.element = checkNotNull(element); } @Override public E get(int index) { Preconditions.checkElementIndex(index, 1); return element; } @Override public int indexOf(@Nullable Object object) { return element.equals(object) ? 0 : -1; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.singletonIterator(element); } @Override public int lastIndexOf(@Nullable Object object) { return indexOf(object); } @Override public int size() { return 1; } @Override public ImmutableList<E> subList(int fromIndex, int toIndex) { Preconditions.checkPositionIndexes(fromIndex, toIndex, 1); return (fromIndex == toIndex) ? ImmutableList.<E>of() : this; } @Override public ImmutableList<E> reverse() { return this; } @Override public boolean contains(@Nullable Object object) { return element.equals(object); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof List) { List<?> that = (List<?>) object; return that.size() == 1 && element.equals(that.get(0)); } return false; } @Override public int hashCode() { // not caching hash code since it could change if the element is mutable // in a way that modifies its hash code. return 31 + element.hashCode(); } @Override public String toString() { String elementToString = element.toString(); return new StringBuilder(elementToString.length() + 2) .append('[') .append(elementToString) .append(']') .toString(); } @Override public boolean isEmpty() { return false; } @Override boolean isPartialView() { return false; } @Override int copyIntoArray(Object[] dst, int offset) { dst[offset] = element; return offset + 1; } }
Java
/* * Copyright (C) 2009 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.checkPositionIndex; import com.google.common.annotations.GwtCompatible; import java.util.ListIterator; import java.util.NoSuchElementException; /** * This class provides a skeletal implementation of the {@link ListIterator} * interface across a fixed number of elements that may be retrieved by * position. It does not support {@link #remove}, {@link #set}, or {@link #add}. * * @author Jared Levy */ @GwtCompatible abstract class AbstractIndexedListIterator<E> extends UnmodifiableListIterator<E> { private final int size; private int position; /** * Returns the element with the specified index. This method is called by * {@link #next()}. */ protected abstract E get(int index); /** * Constructs an iterator across a sequence of the given size whose initial * position is 0. That is, the first call to {@link #next()} will return the * first element (or throw {@link NoSuchElementException} if {@code size} is * zero). * * @throws IllegalArgumentException if {@code size} is negative */ protected AbstractIndexedListIterator(int size) { this(size, 0); } /** * Constructs an iterator across a sequence of the given size with the given * initial position. That is, the first call to {@link #nextIndex()} will * return {@code position}, and the first call to {@link #next()} will return * the element at that index, if available. Calls to {@link #previous()} can * retrieve the preceding {@code position} elements. * * @throws IndexOutOfBoundsException if {@code position} is negative or is * greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ protected AbstractIndexedListIterator(int size, int position) { checkPositionIndex(position, size); this.size = size; this.position = position; } @Override public final boolean hasNext() { return position < size; } @Override public final E next() { if (!hasNext()) { throw new NoSuchElementException(); } return get(position++); } @Override public final int nextIndex() { return position; } @Override public final boolean hasPrevious() { return position > 0; } @Override public final E previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } return get(--position); } @Override public final int previousIndex() { return position - 1; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.io.Serializable; /** * An abstract base class for implementing the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * The {@link #delegate()} method must be overridden to return the instance * being decorated. * * <p>This class does <i>not</i> forward the {@code hashCode} and {@code equals} * methods through to the backing object, but relies on {@code Object}'s * implementation. This is necessary to preserve the symmetry of {@code equals}. * Custom definitions of equality are usually based on an interface, such as * {@code Set} or {@code List}, so that the implementation of {@code equals} can * cast the object being tested for equality to the custom interface. {@code * ForwardingObject} implements no such custom interfaces directly; they * are implemented only in subclasses. Therefore, forwarding {@code equals} * would break symmetry, as the forwarding object might consider itself equal to * the object being tested, but the reverse could not be true. This behavior is * consistent with the JDK's collection wrappers, such as * {@link java.util.Collections#unmodifiableCollection}. Use an * interface-specific subclass of {@code ForwardingObject}, such as {@link * ForwardingList}, to preserve equality behavior, or override {@code equals} * directly. * * <p>The {@code toString} method is forwarded to the delegate. Although this * class does not implement {@link Serializable}, a serializable subclass may be * created since this class has a parameter-less constructor. * * @author Mike Bostock * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public abstract class ForwardingObject { /** Constructor for use by subclasses. */ protected ForwardingObject() {} /** * Returns the backing delegate instance that methods are forwarded to. * Abstract subclasses generally override this method with an abstract method * that has a more specific return type, such as {@link * ForwardingSet#delegate}. Concrete subclasses override this method to supply * the instance being decorated. */ protected abstract Object delegate(); /** * Returns the string representation generated by the delegate's * {@code toString} method. */ @Override public String toString() { return delegate().toString(); } /* No equals or hashCode. See class comments for details. */ }
Java
/* * Copyright (C) 2012 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 static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Maps.ImprovedAbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of {@link Multimaps#filterEntries(Multimap, Predicate)}. * * @author Jared Levy * @author Louis Wasserman */ @GwtCompatible class FilteredEntryMultimap<K, V> extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> { final Multimap<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; FilteredEntryMultimap(Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = checkNotNull(unfiltered); this.predicate = checkNotNull(predicate); } @Override public Multimap<K, V> unfiltered() { return unfiltered; } @Override public Predicate<? super Entry<K, V>> entryPredicate() { return predicate; } @Override public int size() { return entries().size(); } private boolean satisfies(K key, V value) { return predicate.apply(Maps.immutableEntry(key, value)); } final class ValuePredicate implements Predicate<V> { private final K key; ValuePredicate(K key) { this.key = key; } @Override public boolean apply(@Nullable V value) { return satisfies(key, value); } } static <E> Collection<E> filterCollection( Collection<E> collection, Predicate<? super E> predicate) { if (collection instanceof Set) { return Sets.filter((Set<E>) collection, predicate); } else { return Collections2.filter(collection, predicate); } } @Override public boolean containsKey(@Nullable Object key) { return asMap().get(key) != null; } @Override public Collection<V> removeAll(@Nullable Object key) { return Objects.firstNonNull(asMap().remove(key), unmodifiableEmptyCollection()); } Collection<V> unmodifiableEmptyCollection() { // These return false, rather than throwing a UOE, on remove calls. return (unfiltered instanceof SetMultimap) ? Collections.<V>emptySet() : Collections.<V>emptyList(); } @Override public void clear() { entries().clear(); } @Override public Collection<V> get(final K key) { return filterCollection(unfiltered.get(key), new ValuePredicate(key)); } @Override Collection<Entry<K, V>> createEntries() { return filterCollection(unfiltered.entries(), predicate); } @Override Collection<V> createValues() { return new FilteredMultimapValues<K, V>(this); } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Map<K, Collection<V>> createAsMap() { return new AsMap(); } @Override public Set<K> keySet() { return asMap().keySet(); } boolean removeIf(Predicate<? super Entry<K, Collection<V>>> predicate) { Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<K, Collection<V>> entry = entryIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) { if (collection.size() == entry.getValue().size()) { entryIterator.remove(); } else { collection.clear(); } changed = true; } } return changed; } class AsMap extends ImprovedAbstractMap<K, Collection<V>> { @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public void clear() { FilteredEntryMultimap.this.clear(); } @Override public Collection<V> get(@Nullable Object key) { Collection<V> result = unfiltered.asMap().get(key); if (result == null) { return null; } @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself K k = (K) key; result = filterCollection(result, new ValuePredicate(k)); return result.isEmpty() ? null : result; } @Override public Collection<V> remove(@Nullable Object key) { Collection<V> collection = unfiltered.asMap().get(key); if (collection == null) { return null; } @SuppressWarnings("unchecked") // it's definitely equal to a K K k = (K) key; List<V> result = Lists.newArrayList(); Iterator<V> itr = collection.iterator(); while (itr.hasNext()) { V v = itr.next(); if (satisfies(k, v)) { itr.remove(); result.add(v); } } if (result.isEmpty()) { return null; } else if (unfiltered instanceof SetMultimap) { return Collections.unmodifiableSet(Sets.newLinkedHashSet(result)); } else { return Collections.unmodifiableList(result); } } @Override Set<K> createKeySet() { return new Maps.KeySet<K, Collection<V>>(this) { @Override public boolean removeAll(Collection<?> c) { return removeIf(Maps.<K>keyPredicateOnEntries(in(c))); } @Override public boolean retainAll(Collection<?> c) { return removeIf(Maps.<K>keyPredicateOnEntries(not(in(c)))); } @Override public boolean remove(@Nullable Object o) { return AsMap.this.remove(o) != null; } }; } @Override Set<Entry<K, Collection<V>>> createEntrySet() { return new Maps.EntrySet<K, Collection<V>>() { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return new AbstractIterator<Entry<K, Collection<V>>>() { final Iterator<Entry<K, Collection<V>>> backingIterator = unfiltered.asMap().entrySet().iterator(); @Override protected Entry<K, Collection<V>> computeNext() { while (backingIterator.hasNext()) { Entry<K, Collection<V>> entry = backingIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty()) { return Maps.immutableEntry(key, collection); } } return endOfData(); } }; } @Override public boolean removeAll(Collection<?> c) { return removeIf(in(c)); } @Override public boolean retainAll(Collection<?> c) { return removeIf(not(in(c))); } @Override public int size() { return Iterators.size(iterator()); } }; } @Override Collection<Collection<V>> createValues() { return new Maps.Values<K, Collection<V>>(AsMap.this) { @Override public boolean remove(@Nullable Object o) { if (o instanceof Collection) { Collection<?> c = (Collection<?>) o; Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator(); while (entryIterator.hasNext()) { Entry<K, Collection<V>> entry = entryIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty() && c.equals(collection)) { if (collection.size() == entry.getValue().size()) { entryIterator.remove(); } else { collection.clear(); } return true; } } } return false; } @Override public boolean removeAll(Collection<?> c) { return removeIf(Maps.<Collection<V>>valuePredicateOnEntries(in(c))); } @Override public boolean retainAll(Collection<?> c) { return removeIf(Maps.<Collection<V>>valuePredicateOnEntries(not(in(c)))); } }; } } @Override Multiset<K> createKeys() { return new Keys(); } class Keys extends Multimaps.Keys<K, V> { Keys() { super(FilteredEntryMultimap.this); } @Override public int remove(@Nullable Object key, int occurrences) { Multisets.checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(key); } Collection<V> collection = unfiltered.asMap().get(key); if (collection == null) { return 0; } @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself K k = (K) key; int oldCount = 0; Iterator<V> itr = collection.iterator(); while (itr.hasNext()) { V v = itr.next(); if (satisfies(k, v)) { oldCount++; if (oldCount <= occurrences) { itr.remove(); } } } return oldCount; } @Override public Set<Multiset.Entry<K>> entrySet() { return new Multisets.EntrySet<K>() { @Override Multiset<K> multiset() { return Keys.this; } @Override public Iterator<Multiset.Entry<K>> iterator() { return Keys.this.entryIterator(); } @Override public int size() { return FilteredEntryMultimap.this.keySet().size(); } private boolean removeIf(final Predicate<? super Multiset.Entry<K>> predicate) { return FilteredEntryMultimap.this.removeIf(new Predicate<Map.Entry<K, Collection<V>>>() { @Override public boolean apply(Map.Entry<K, Collection<V>> entry) { return predicate.apply( Multisets.immutableEntry(entry.getKey(), entry.getValue().size())); } }); } @Override public boolean removeAll(Collection<?> c) { return removeIf(in(c)); } @Override public boolean retainAll(Collection<?> c) { return removeIf(not(in(c))); } }; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.not; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import javax.annotation.Nullable; /** * This class contains static utility methods that operate on or return objects * of type {@link Iterator}. Except as noted, each method has a corresponding * {@link Iterable}-based method in the {@link Iterables} class. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterators * produced in this class are <i>lazy</i>, which means that they only advance * the backing iteration when absolutely necessary. * * <p>See the Guava User Guide section on <a href= * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Iterables"> * {@code Iterators}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Iterators { private Iterators() {} static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR = new UnmodifiableListIterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public boolean hasPrevious() { return false; } @Override public Object previous() { throw new NoSuchElementException(); } @Override public int nextIndex() { return 0; } @Override public int previousIndex() { return -1; } }; /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ public static <T> UnmodifiableIterator<T> emptyIterator() { return emptyListIterator(); } /** * Returns the empty iterator. * * <p>The {@link Iterable} equivalent of this method is {@link * ImmutableSet#of()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> UnmodifiableListIterator<T> emptyListIterator() { return (UnmodifiableListIterator<T>) EMPTY_LIST_ITERATOR; } private static final Iterator<Object> EMPTY_MODIFIABLE_ITERATOR = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }; /** * Returns the empty {@code Iterator} that throws * {@link IllegalStateException} instead of * {@link UnsupportedOperationException} on a call to * {@link Iterator#remove()}. */ // Casting to any type is safe since there are no actual elements. @SuppressWarnings("unchecked") static <T> Iterator<T> emptyModifiableIterator() { return (Iterator<T>) EMPTY_MODIFIABLE_ITERATOR; } /** Returns an unmodifiable view of {@code iterator}. */ public static <T> UnmodifiableIterator<T> unmodifiableIterator( final Iterator<T> iterator) { checkNotNull(iterator); if (iterator instanceof UnmodifiableIterator) { return (UnmodifiableIterator<T>) iterator; } return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return iterator.next(); } }; } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> UnmodifiableIterator<T> unmodifiableIterator( UnmodifiableIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. */ public static int size(Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } /** * Returns {@code true} if {@code iterator} contains {@code element}. */ public static boolean contains(Iterator<?> iterator, @Nullable Object element) { return any(iterator, equalTo(element)); } /** * Traverses an iterator and removes every element that belongs to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterator} */ public static boolean removeAll( Iterator<?> removeFrom, Collection<?> elementsToRemove) { return removeIf(removeFrom, in(elementsToRemove)); } /** * Removes every element that satisfies the provided predicate from the * iterator. The iterator will be left exhausted: its {@code hasNext()} * method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param predicate a predicate that determines whether an element should * be removed * @return {@code true} if any elements were removed from the iterator * @since 2.0 */ public static <T> boolean removeIf( Iterator<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); boolean modified = false; while (removeFrom.hasNext()) { if (predicate.apply(removeFrom.next())) { removeFrom.remove(); modified = true; } } return modified; } /** * Traverses an iterator and removes every element that does not belong to the * provided collection. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @param removeFrom the iterator to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterator} */ public static boolean retainAll( Iterator<?> removeFrom, Collection<?> elementsToRetain) { return removeIf(removeFrom, not(in(elementsToRetain))); } /** * Determines whether two iterators contain equal elements in the same order. * More specifically, this method returns {@code true} if {@code iterator1} * and {@code iterator2} contain the same number of elements and every element * of {@code iterator1} is equal to the corresponding element of * {@code iterator2}. * * <p>Note that this will modify the supplied iterators, since they will have * been advanced some number of elements forward. */ public static boolean elementsEqual( Iterator<?> iterator1, Iterator<?> iterator2) { while (iterator1.hasNext()) { if (!iterator2.hasNext()) { return false; } Object o1 = iterator1.next(); Object o2 = iterator2.next(); if (!Objects.equal(o1, o2)) { return false; } } return !iterator2.hasNext(); } /** * Returns a string representation of {@code iterator}, with the format * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. */ public static String toString(Iterator<?> iterator) { return Collections2.STANDARD_JOINER .appendTo(new StringBuilder().append('['), iterator) .append(']') .toString(); } /** * Returns the single element contained in {@code iterator}. * * @throws NoSuchElementException if the iterator is empty * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ public static <T> T getOnlyElement(Iterator<T> iterator) { T first = iterator.next(); if (!iterator.hasNext()) { return first; } StringBuilder sb = new StringBuilder(); sb.append("expected one element but was: <" + first); for (int i = 0; i < 4 && iterator.hasNext(); i++) { sb.append(", " + iterator.next()); } if (iterator.hasNext()) { sb.append(", ..."); } sb.append('>'); throw new IllegalArgumentException(sb.toString()); } /** * Returns the single element contained in {@code iterator}, or {@code * defaultValue} if the iterator is empty. * * @throws IllegalArgumentException if the iterator contains multiple * elements. The state of the iterator is unspecified. */ @Nullable public static <T> T getOnlyElement(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; } /** * Copies an iterator's elements into an array. The iterator will be left * exhausted: its {@code hasNext()} method will return {@code false}. * * @param iterator the iterator to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterator * have been copied */ @GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] toArray( Iterator<? extends T> iterator, Class<T> type) { List<T> list = Lists.newArrayList(iterator); return Iterables.toArray(list, type); } /** * Adds all elements in {@code iterator} to {@code collection}. The iterator * will be left exhausted: its {@code hasNext()} method will return * {@code false}. * * @return {@code true} if {@code collection} was modified as a result of this * operation */ public static <T> boolean addAll( Collection<T> addTo, Iterator<? extends T> iterator) { checkNotNull(addTo); checkNotNull(iterator); boolean wasModified = false; while (iterator.hasNext()) { wasModified |= addTo.add(iterator.next()); } return wasModified; } /** * Returns the number of elements in the specified iterator that equal the * specified object. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * @see Collections#frequency */ public static int frequency(Iterator<?> iterator, @Nullable Object element) { return size(filter(iterator, equalTo(element))); } /** * Returns an iterator that cycles indefinitely over the elements of {@code * iterable}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After {@code remove()} is called, subsequent cycles omit the removed * element, which is no longer in {@code iterable}. The iterator's * {@code hasNext()} method returns {@code true} until {@code iterable} is * empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new Iterator<T>() { Iterator<T> iterator = emptyIterator(); Iterator<T> removeFrom; @Override public boolean hasNext() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = iterator; return iterator.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Returns an iterator that cycles indefinitely over the provided elements. * * <p>The returned iterator supports {@code remove()}. After {@code remove()} * is called, subsequent cycles omit the removed * element, but {@code elements} does not change. The iterator's * {@code hasNext()} method returns {@code true} until all of the original * elements have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an * infinite loop. You should use an explicit {@code break} or be certain that * you will eventually remove all the elements. */ public static <T> Iterator<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) { return concat(ImmutableList.of(a, b).iterator()); } /** * Combines three iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}. The source iterators * are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) { return concat(ImmutableList.of(a, b, c).iterator()); } /** * Combines four iterators into a single iterator. The returned iterator * iterates across the elements in {@code a}, followed by the elements in * {@code b}, followed by the elements in {@code c}, followed by the elements * in {@code d}. The source iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c, Iterator<? extends T> d) { return concat(ImmutableList.of(a, b, c, d).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. * * @throws NullPointerException if any of the provided iterators is null */ public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) { return concat(ImmutableList.copyOf(inputs).iterator()); } /** * Combines multiple iterators into a single iterator. The returned iterator * iterates across the elements of each iterator in {@code inputs}. The input * iterators are not polled until necessary. * * <p>The returned iterator supports {@code remove()} when the corresponding * input iterator supports it. The methods of the returned iterator may throw * {@code NullPointerException} if any of the input iterators is null. * * <p><b>Note:</b> the current implementation is not suitable for nested * concatenated iterators, i.e. the following should be avoided when in a loop: * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over the * resulting iterator has a cubic complexity to the depth of the nesting. */ public static <T> Iterator<T> concat( final Iterator<? extends Iterator<? extends T>> inputs) { checkNotNull(inputs); return new Iterator<T>() { Iterator<? extends T> current = emptyIterator(); Iterator<? extends T> removeFrom; @Override public boolean hasNext() { // http://code.google.com/p/google-collections/issues/detail?id=151 // current.hasNext() might be relatively expensive, worth minimizing. boolean currentHasNext; // checkNotNull eager for GWT // note: it must be here & not where 'current' is assigned, // because otherwise we'll have called inputs.next() before throwing // the first NPE, and the next time around we'll call inputs.next() // again, incorrectly moving beyond the error. while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { current = inputs.next(); } return currentHasNext; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } removeFrom = current; return current.next(); } @Override public void remove() { checkRemove(removeFrom != null); removeFrom.remove(); removeFrom = null; } }; } /** * Divides an iterator into unmodifiable sublists of the given size (the final * list may be smaller). For example, partitioning an iterator containing * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of * three and two elements, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> partition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, false); } /** * Divides an iterator into unmodifiable sublists of the given size, padding * the final iterator with null values if necessary. For example, partitioning * an iterator containing {@code [a, b, c, d, e]} with a partition size of 3 * yields {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing * two inner lists of three elements each, all in the original order. * * <p>The returned lists implement {@link java.util.RandomAccess}. * * @param iterator the iterator to return a partitioned view of * @param size the desired size of each partition * @return an iterator of immutable lists containing the elements of {@code * iterator} divided into partitions (the final iterable may have * trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T> UnmodifiableIterator<List<T>> paddedPartition( Iterator<T> iterator, int size) { return partitionImpl(iterator, size, true); } private static <T> UnmodifiableIterator<List<T>> partitionImpl( final Iterator<T> iterator, final int size, final boolean pad) { checkNotNull(iterator); checkArgument(size > 0); return new UnmodifiableIterator<List<T>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } Object[] array = new Object[size]; int count = 0; for (; count < size && iterator.hasNext(); count++) { array[count] = iterator.next(); } for (int i = count; i < size; i++) { array[i] = null; // for GWT } @SuppressWarnings("unchecked") // we only put Ts in it List<T> list = Collections.unmodifiableList( (List<T>) Arrays.asList(array)); return (pad || count == size) ? list : list.subList(0, count); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. */ public static <T> UnmodifiableIterator<T> filter( final Iterator<T> unfiltered, final Predicate<? super T> predicate) { checkNotNull(unfiltered); checkNotNull(predicate); return new AbstractIterator<T>() { @Override protected T computeNext() { while (unfiltered.hasNext()) { T element = unfiltered.next(); if (predicate.apply(element)) { return element; } } return endOfData(); } }; } /** * Returns all instances of class {@code type} in {@code unfiltered}. The * returned iterator has elements whose class is {@code type} or a subclass of * {@code type}. * * @param unfiltered an iterator containing objects of any type * @param type the type of elements desired * @return an unmodifiable iterator containing all elements of the original * iterator that were of the requested type */ @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed @GwtIncompatible("Class.isInstance") public static <T> UnmodifiableIterator<T> filter( Iterator<?> unfiltered, Class<T> type) { return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(type)); } /** * Returns {@code true} if one or more elements returned by {@code iterator} * satisfy the given predicate. */ public static <T> boolean any( Iterator<T> iterator, Predicate<? super T> predicate) { return indexOf(iterator, predicate) != -1; } /** * Returns {@code true} if every element returned by {@code iterator} * satisfies the given predicate. If {@code iterator} is empty, {@code true} * is returned. */ public static <T> boolean all( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate); while (iterator.hasNext()) { T element = iterator.next(); if (!predicate.apply(element)) { return false; } } return true; } /** * Returns the first element in {@code iterator} that satisfies the given * predicate; use this method only when such an element is known to exist. If * no such element is found, the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. If it is possible that * <i>no</i> element will match, use {@link #tryFind} or {@link * #find(Iterator, Predicate, Object)} instead. * * @throws NoSuchElementException if no element in {@code iterator} matches * the given predicate */ public static <T> T find( Iterator<T> iterator, Predicate<? super T> predicate) { return filter(iterator, predicate).next(); } /** * Returns the first element in {@code iterator} that satisfies the given * predicate. If no such element is found, {@code defaultValue} will be * returned from this method and the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Note that this can * usually be handled more naturally using {@code * tryFind(iterator, predicate).or(defaultValue)}. * * @since 7.0 */ @Nullable public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) { return getNext(filter(iterator, predicate), defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code * iterator} that satisfies the given predicate, if such an element exists. If * no such element is found, an empty {@link Optional} will be returned from * this method and the iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code * null}. If {@code null} is matched in {@code iterator}, a * NullPointerException will be thrown. * * @since 11.0 */ public static <T> Optional<T> tryFind( Iterator<T> iterator, Predicate<? super T> predicate) { UnmodifiableIterator<T> filteredIterator = filter(iterator, predicate); return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.<T>absent(); } /** * Returns the index in {@code iterator} of the first element that satisfies * the provided {@code predicate}, or {@code -1} if the Iterator has no such * elements. * * <p>More formally, returns the lowest index {@code i} such that * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, * or {@code -1} if there is no such index. * * <p>If -1 is returned, the iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. Otherwise, * the iterator will be set to the element which satisfies the * {@code predicate}. * * @since 2.0 */ public static <T> int indexOf( Iterator<T> iterator, Predicate<? super T> predicate) { checkNotNull(predicate, "predicate"); for (int i = 0; iterator.hasNext(); i++) { T current = iterator.next(); if (predicate.apply(current)) { return i; } } return -1; } /** * Returns an iterator that applies {@code function} to each element of {@code * fromIterator}. * * <p>The returned iterator supports {@code remove()} if the provided iterator * does. After a successful {@code remove()} call, {@code fromIterator} no * longer contains the corresponding element. */ public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { checkNotNull(function); return new TransformedIterator<F, T>(fromIterator) { @Override T transform(F from) { return function.apply(from); } }; } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position. * * @param position position of the element to return * @return the element at the specified position in {@code iterator} * @throws IndexOutOfBoundsException if {@code position} is negative or * greater than or equal to the number of elements remaining in * {@code iterator} */ public static <T> T get(Iterator<T> iterator, int position) { checkNonnegative(position); int skipped = advance(iterator, position); if (!iterator.hasNext()) { throw new IndexOutOfBoundsException("position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } return iterator.next(); } static void checkNonnegative(int position) { if (position < 0) { throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); } } /** * Advances {@code iterator} {@code position + 1} times, returning the * element at the {@code position}th position or {@code defaultValue} * otherwise. * * @param position position of the element to return * @param defaultValue the default value to return if the iterator is empty * or if {@code position} is greater than the number of elements * remaining in {@code iterator} * @return the element at the specified position in {@code iterator} or * {@code defaultValue} if {@code iterator} produces fewer than * {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @Nullable public static <T> T get(Iterator<? extends T> iterator, int position, @Nullable T defaultValue) { checkNonnegative(position); advance(iterator, position); return getNext(iterator, defaultValue); } /** * Returns the next element in {@code iterator} or {@code defaultValue} if * the iterator is empty. The {@link Iterables} analog to this method is * {@link Iterables#getFirst}. * * @param defaultValue the default value to return if the iterator is empty * @return the next element of {@code iterator} or the default value * @since 7.0 */ @Nullable public static <T> T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? iterator.next() : defaultValue; } /** * Advances {@code iterator} to the end, returning the last element. * * @return the last element of {@code iterator} * @throws NoSuchElementException if the iterator is empty */ public static <T> T getLast(Iterator<T> iterator) { while (true) { T current = iterator.next(); if (!iterator.hasNext()) { return current; } } } /** * Advances {@code iterator} to the end, returning the last element or * {@code defaultValue} if the iterator is empty. * * @param defaultValue the default value to return if the iterator is empty * @return the last element of {@code iterator} * @since 3.0 */ @Nullable public static <T> T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) { return iterator.hasNext() ? getLast(iterator) : defaultValue; } /** * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times * or until {@code hasNext()} returns {@code false}, whichever comes first. * * @return the number of elements the iterator was advanced * @since 13.0 (since 3.0 as {@code Iterators.skip}) */ public static int advance(Iterator<?> iterator, int numberToAdvance) { checkNotNull(iterator); checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); int i; for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { iterator.next(); } return i; } /** * Creates an iterator returning the first {@code limitSize} elements of the * given iterator. If the original iterator does not contain that many * elements, the returned iterator will have the same behavior as the original * iterator. The returned iterator supports {@code remove()} if the original * iterator does. * * @param iterator the iterator to limit * @param limitSize the maximum number of elements in the returned iterator * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T> Iterator<T> limit( final Iterator<T> iterator, final int limitSize) { checkNotNull(iterator); checkArgument(limitSize >= 0, "limit is negative"); return new Iterator<T>() { private int count; @Override public boolean hasNext() { return count < limitSize && iterator.hasNext(); } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } /** * Returns a view of the supplied {@code iterator} that removes each element * from the supplied {@code iterator} as it is returned. * * <p>The provided iterator must support {@link Iterator#remove()} or * else the returned iterator will fail on the first call to {@code * next}. * * @param iterator the iterator to remove and return elements from * @return an iterator that removes and returns elements from the * supplied iterator * @since 2.0 */ public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) { checkNotNull(iterator); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { T next = iterator.next(); iterator.remove(); return next; } }; } /** * Deletes and returns the next value from the iterator, or returns * {@code defaultValue} if there is no such value. */ @Nullable static <T> T pollNext(Iterator<T> iterator) { if (iterator.hasNext()) { T result = iterator.next(); iterator.remove(); return result; } else { return null; } } // Methods only in Iterators, not in Iterables /** * Clears the iterator using its remove method. */ static void clear(Iterator<?> iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } /** * Returns an iterator containing the elements of {@code array} in order. The * returned iterator is a view of the array; subsequent changes to the array * will be reflected in the iterator. * * <p><b>Note:</b> It is often preferable to represent your data using a * collection type, for example using {@link Arrays#asList(Object[])}, making * this method unnecessary. * * <p>The {@code Iterable} equivalent of this method is either {@link * Arrays#asList(Object[])}, {@link ImmutableList#copyOf(Object[])}}, * or {@link ImmutableList#of}. */ public static <T> UnmodifiableIterator<T> forArray(final T... array) { return forArray(array, 0, array.length, 0); } /** * Returns a list iterator containing the elements in the specified range of * {@code array} in order, starting at the specified index. * * <p>The {@code Iterable} equivalent of this method is {@code * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}. */ static <T> UnmodifiableListIterator<T> forArray( final T[] array, final int offset, int length, int index) { checkArgument(length >= 0); int end = offset + length; // Technically we should give a slightly more descriptive error on overflow Preconditions.checkPositionIndexes(offset, end, array.length); Preconditions.checkPositionIndex(index, length); if (length == 0) { return emptyListIterator(); } /* * We can't use call the two-arg constructor with arguments (offset, end) * because the returned Iterator is a ListIterator that may be moved back * past the beginning of the iteration. */ return new AbstractIndexedListIterator<T>(length, index) { @Override protected T get(int index) { return array[offset + index]; } }; } /** * Returns an iterator containing only {@code value}. * * <p>The {@link Iterable} equivalent of this method is {@link * Collections#singleton}. */ public static <T> UnmodifiableIterator<T> singletonIterator( @Nullable final T value) { return new UnmodifiableIterator<T>() { boolean done; @Override public boolean hasNext() { return !done; } @Override public T next() { if (done) { throw new NoSuchElementException(); } done = true; return value; } }; } /** * Adapts an {@code Enumeration} to the {@code Iterator} interface. * * <p>This method has no equivalent in {@link Iterables} because viewing an * {@code Enumeration} as an {@code Iterable} is impossible. However, the * contents can be <i>copied</i> into a collection using {@link * Collections#list}. */ public static <T> UnmodifiableIterator<T> forEnumeration( final Enumeration<T> enumeration) { checkNotNull(enumeration); return new UnmodifiableIterator<T>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public T next() { return enumeration.nextElement(); } }; } /** * Adapts an {@code Iterator} to the {@code Enumeration} interface. * * <p>The {@code Iterable} equivalent of this method is either {@link * Collections#enumeration} (if you have a {@link Collection}), or * {@code Iterators.asEnumeration(collection.iterator())}. */ public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) { checkNotNull(iterator); return new Enumeration<T>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public T nextElement() { return iterator.next(); } }; } /** * Implementation of PeekingIterator that avoids peeking unless necessary. */ private static class PeekingImpl<E> implements PeekingIterator<E> { private final Iterator<? extends E> iterator; private boolean hasPeeked; private E peekedElement; public PeekingImpl(Iterator<? extends E> iterator) { this.iterator = checkNotNull(iterator); } @Override public boolean hasNext() { return hasPeeked || iterator.hasNext(); } @Override public E next() { if (!hasPeeked) { return iterator.next(); } E result = peekedElement; hasPeeked = false; peekedElement = null; return result; } @Override public void remove() { checkState(!hasPeeked, "Can't remove after you've peeked at next"); iterator.remove(); } @Override public E peek() { if (!hasPeeked) { peekedElement = iterator.next(); hasPeeked = true; } return peekedElement; } } /** * Returns a {@code PeekingIterator} backed by the given iterator. * * <p>Calls to the {@code peek} method with no intervening calls to {@code * next} do not affect the iteration, and hence return the same object each * time. A subsequent call to {@code next} is guaranteed to return the same * object again. For example: <pre> {@code * * PeekingIterator<String> peekingIterator = * Iterators.peekingIterator(Iterators.forArray("a", "b")); * String a1 = peekingIterator.peek(); // returns "a" * String a2 = peekingIterator.peek(); // also returns "a" * String a3 = peekingIterator.next(); // also returns "a"}</pre> * * <p>Any structural changes to the underlying iteration (aside from those * performed by the iterator's own {@link PeekingIterator#remove()} method) * will leave the iterator in an undefined state. * * <p>The returned iterator does not support removal after peeking, as * explained by {@link PeekingIterator#remove()}. * * <p>Note: If the given iterator is already a {@code PeekingIterator}, * it <i>might</i> be returned to the caller, although this is neither * guaranteed to occur nor required to be consistent. For example, this * method <i>might</i> choose to pass through recognized implementations of * {@code PeekingIterator} when the behavior of the implementation is * known to meet the contract guaranteed by this method. * * <p>There is no {@link Iterable} equivalent to this method, so use this * method to wrap each individual iterator as it is generated. * * @param iterator the backing iterator. The {@link PeekingIterator} assumes * ownership of this iterator, so users should cease making direct calls * to it after calling this method. * @return a peeking iterator backed by that iterator. Apart from the * additional {@link PeekingIterator#peek()} method, this iterator behaves * exactly the same as {@code iterator}. */ public static <T> PeekingIterator<T> peekingIterator( Iterator<? extends T> iterator) { if (iterator instanceof PeekingImpl) { // Safe to cast <? extends T> to <T> because PeekingImpl only uses T // covariantly (and cannot be subclassed to add non-covariant uses). @SuppressWarnings("unchecked") PeekingImpl<T> peeking = (PeekingImpl<T>) iterator; return peeking; } return new PeekingImpl<T>(iterator); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <T> PeekingIterator<T> peekingIterator( PeekingIterator<T> iterator) { return checkNotNull(iterator); } /** * Returns an iterator over the merged contents of all given * {@code iterators}, traversing every element of the input iterators. * Equivalent entries will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterators} are in * non-descending order as this method does not sort its input. * * <p>For any equivalent elements across all {@code iterators}, it is * undefined which element is returned first. * * @since 11.0 */ @Beta public static <T> UnmodifiableIterator<T> mergeSorted( Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) { checkNotNull(iterators, "iterators"); checkNotNull(comparator, "comparator"); return new MergingIterator<T>(iterators, comparator); } /** * An iterator that performs a lazy N-way merge, calculating the next value * each time the iterator is polled. This amortizes the sorting cost over the * iteration and requires less memory than sorting all elements at once. * * <p>Retrieving a single element takes approximately O(log(M)) time, where M * is the number of iterators. (Retrieving all elements takes approximately * O(N*log(M)) time, where N is the total number of elements.) */ private static class MergingIterator<T> extends UnmodifiableIterator<T> { final Queue<PeekingIterator<T>> queue; public MergingIterator(Iterable<? extends Iterator<? extends T>> iterators, final Comparator<? super T> itemComparator) { // A comparator that's used by the heap, allowing the heap // to be sorted based on the top of each iterator. Comparator<PeekingIterator<T>> heapComparator = new Comparator<PeekingIterator<T>>() { @Override public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) { return itemComparator.compare(o1.peek(), o2.peek()); } }; queue = new PriorityQueue<PeekingIterator<T>>(2, heapComparator); for (Iterator<? extends T> iterator : iterators) { if (iterator.hasNext()) { queue.add(Iterators.peekingIterator(iterator)); } } } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public T next() { PeekingIterator<T> nextIter = queue.remove(); T next = nextIter.next(); if (nextIter.hasNext()) { queue.add(nextIter); } return next; } } /** * Precondition tester for {@code Iterator.remove()} that throws an exception with a consistent * error message. */ static void checkRemove(boolean canRemove) { checkState(canRemove, "no calls to next() since the last call to remove()"); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T> ListIterator<T> cast(Iterator<T> iterator) { return (ListIterator<T>) iterator; } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Map; /** * An immutable {@link BiMap} with reliable user-specified iteration order. Does * not permit null keys or values. An {@code ImmutableBiMap} and its inverse * have the same iteration ordering. * * <p>An instance of {@code ImmutableBiMap} contains its own data and will * <i>never</i> change. {@code ImmutableBiMap} is convenient for * {@code public static final} maps ("constant maps") and also lets you easily * make a "defensive copy" of a bimap provided to your class by a caller. * * <p><b>Note:</b> Although this class is not final, it cannot be subclassed as * it has no public or protected constructors. Thus, instances of this class are * guaranteed to be immutable. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) public abstract class ImmutableBiMap<K, V> extends ImmutableMap<K, V> implements BiMap<K, V> { /** * Returns the empty bimap. */ // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings("unchecked") public static <K, V> ImmutableBiMap<K, V> of() { return (ImmutableBiMap<K, V>) EmptyImmutableBiMap.INSTANCE; } /** * Returns an immutable bimap containing a single entry. */ public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { return new SingletonImmutableBiMap<K, V>(k1, v1); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys or values are added */ public static <K, V> ImmutableBiMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableBiMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } /** * A builder for creating immutable bimap instances, especially {@code public * static final} bimaps ("constant bimaps"). Example: <pre> {@code * * static final ImmutableBiMap<String, Integer> WORD_TO_INT = * new ImmutableBiMap.Builder<String, Integer>() * .put("one", 1) * .put("two", 2) * .put("three", 3) * .build();}</pre> * * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods * are even more convenient. * * <p>Builder instances can be reused - it is safe to call {@link #build} * multiple times to build multiple bimaps in series. Each bimap is a superset * of the bimaps created before it. * * @since 2.0 (imported from Google Collections Library) */ public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableBiMap#builder}. */ public Builder() {} /** * Associates {@code key} with {@code value} in the built bimap. Duplicate * keys or values are not allowed, and will cause {@link #build} to fail. */ @Override public Builder<K, V> put(K key, V value) { super.put(key, value); return this; } /** * Associates all of the given map's keys and values in the built bimap. * Duplicate keys or values are not allowed, and will cause {@link #build} * to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ @Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { super.putAll(map); return this; } /** * Returns a newly-created immutable bimap. * * @throws IllegalArgumentException if duplicate keys or values were added */ @Override public ImmutableBiMap<K, V> build() { switch (size) { case 0: return of(); case 1: return of(entries[0].getKey(), entries[0].getValue()); default: return new RegularImmutableBiMap<K, V>(size, entries); } } } /** * Returns an immutable bimap containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p>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. * * @throws IllegalArgumentException if two keys have the same value * @throws NullPointerException if any key or value in {@code map} is null */ public static <K, V> ImmutableBiMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if (map instanceof ImmutableBiMap) { @SuppressWarnings("unchecked") // safe since map is not writable ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; // TODO(user): if we need to make a copy of a BiMap because the // forward map is a view, don't make a copy of the non-view delegate map if (!bimap.isPartialView()) { return bimap; } } Entry<?, ?>[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); switch (entries.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // safe covariant cast in this context Entry<K, V> entry = (Entry<K, V>) entries[0]; return of(entry.getKey(), entry.getValue()); default: return new RegularImmutableBiMap<K, V>(entries); } } private static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; ImmutableBiMap() {} /** * {@inheritDoc} * * <p>The inverse of an {@code ImmutableBiMap} is another * {@code ImmutableBiMap}. */ @Override public abstract ImmutableBiMap<V, K> inverse(); /** * Returns an immutable set of the values in this map. The values are in the * same order as the parameters used to build this map. */ @Override public ImmutableSet<V> values() { return inverse().keySet(); } /** * Guaranteed to throw an exception and leave the bimap unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); } /** * Serialized type for all ImmutableBiMap instances. It captures the logical * contents and they are reconstructed using public factory methods. This * ensures that the implementation types remain as implementation details. * * Since the bimap is immutable, ImmutableBiMap doesn't require special logic * for keeping the bimap and its inverse in sync during serialization, the way * AbstractBiMap does. */ private static class SerializedForm extends ImmutableMap.SerializedForm { SerializedForm(ImmutableBiMap<?, ?> bimap) { super(bimap); } @Override Object readResolve() { Builder<Object, Object> builder = new Builder<Object, Object>(); return createMap(builder); } private static final long serialVersionUID = 0; } @Override Object writeReplace() { return new SerializedForm(this); } }
Java
/* * 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 com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableMapEntry.TerminalEntry; import java.io.Serializable; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.annotation.Nullable; /** * An immutable, hash-based {@link Map} with reliable user-specified iteration * order. Does not permit null keys or values. * * <p>Unlike {@link Collections#unmodifiableMap}, which is a <i>view</i> of a * separate map which can still change, an instance of {@code ImmutableMap} * contains its own data and will <i>never</i> change. {@code ImmutableMap} is * convenient for {@code public static final} maps ("constant maps") and also * lets you easily make a "defensive copy" of a map provided to your class by a * caller. * * <p><i>Performance notes:</i> unlike {@link HashMap}, {@code ImmutableMap} is * not optimized for element types that have slow {@link Object#equals} or * {@link Object#hashCode} implementations. You can get better performance by * having your element type cache its own hash codes, and by making use of the * cached values to short-circuit a slow {@code equals} algorithm. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable { /** * Returns the empty map. This map behaves and performs comparably to * {@link Collections#emptyMap}, and is preferable mainly for consistency * and maintainability of your code. */ public static <K, V> ImmutableMap<K, V> of() { return ImmutableBiMap.of(); } /** * Returns an immutable map containing a single entry. This map behaves and * performs comparably to {@link Collections#singletonMap} but will not accept * a null key or value. It is preferable mainly for consistency and * maintainability of your code. */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1) { return ImmutableBiMap.of(k1, v1); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { return new RegularImmutableMap<K, V>( entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); } /** * Returns an immutable map containing the given entries, in order. * * @throws IllegalArgumentException if duplicate keys are provided */ public static <K, V> ImmutableMap<K, V> of( K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); } // looking for of() with > 5 entries? Use the builder instead. /** * Verifies that {@code key} and {@code value} are non-null, and returns a new * immutable entry with those values. * * <p>A call to {@link Map.Entry#setValue} on the returned entry will always * throw {@link UnsupportedOperationException}. */ static <K, V> TerminalEntry<K, V> entryOf(K key, V value) { checkEntryNotNull(key, value); return new TerminalEntry<K, V>(key, value); } static void checkEntryNotNull(Object key, Object value) { if (key == null) { throw new NullPointerException("null key in entry: null=" + value); } else if (value == null) { throw new NullPointerException("null value in entry: " + key + "=null"); } } /** * Returns a new builder. The generated builder is equivalent to the builder * created by the {@link Builder} constructor. */ public static <K, V> Builder<K, V> builder() { return new Builder<K, V>(); } static void checkNoConflict(boolean safe, String conflictDescription, Entry<?, ?> entry1, Entry<?, ?> entry2) { if (!safe) { throw new IllegalArgumentException( "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); } } /** * A builder for creating immutable map instances, especially {@code public * static final} maps ("constant maps"). Example: <pre> {@code * * static final ImmutableMap<String, Integer> WORD_TO_INT = * new ImmutableMap.Builder<String, Integer>() * .put("one", 1) * .put("two", 2) * .put("three", 3) * .build();}</pre> * * <p>For <i>small</i> immutable maps, the {@code ImmutableMap.of()} methods are * even more convenient. * * <p>Builder instances can be reused - it is safe to call {@link #build} * multiple times to build multiple maps in series. Each map is a superset of * the maps created before it. * * @since 2.0 (imported from Google Collections Library) */ public static class Builder<K, V> { TerminalEntry<K, V>[] entries; int size; /** * Creates a new builder. The returned builder is equivalent to the builder * generated by {@link ImmutableMap#builder}. */ public Builder() { this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); } @SuppressWarnings("unchecked") Builder(int initialCapacity) { this.entries = new TerminalEntry[initialCapacity]; this.size = 0; } private void ensureCapacity(int minCapacity) { if (minCapacity > entries.length) { entries = ObjectArrays.arraysCopyOf( entries, ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity)); } } /** * Associates {@code key} with {@code value} in the built map. Duplicate * keys are not allowed, and will cause {@link #build} to fail. */ public Builder<K, V> put(K key, V value) { ensureCapacity(size + 1); TerminalEntry<K, V> entry = entryOf(key, value); // don't inline this: we want to fail atomically if key or value is null entries[size++] = entry; return this; } /** * Adds the given {@code entry} to the map, making it immutable if * necessary. Duplicate keys are not allowed, and will cause {@link #build} * to fail. * * @since 11.0 */ public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { put(entry.getKey(), entry.getValue()); return this; } /** * Associates all of the given map's keys and values in the built map. * Duplicate keys are not allowed, and will cause {@link #build} to fail. * * @throws NullPointerException if any key or value in {@code map} is null */ public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { ensureCapacity(size + map.size()); for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry); } return this; } /* * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap * versions throw an IllegalStateException instead? */ /** * Returns a newly-created immutable map. * * @throws IllegalArgumentException if duplicate keys were added */ public ImmutableMap<K, V> build() { switch (size) { case 0: return of(); case 1: return of(entries[0].getKey(), entries[0].getValue()); default: return new RegularImmutableMap<K, V>(size, entries); } } } /** * Returns an immutable map containing the same entries as {@code map}. If * {@code map} somehow contains entries with duplicate keys (for example, if * it is a {@code SortedMap} whose comparator is not <i>consistent with * equals</i>), the results of this method are undefined. * * <p>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. * * @throws NullPointerException if any key or value in {@code map} is null */ public static <K, V> ImmutableMap<K, V> copyOf( Map<? extends K, ? extends V> map) { if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { // TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf() // on the ImmutableMap delegate(), rather than the bimap itself @SuppressWarnings("unchecked") // safe since map is not writable ImmutableMap<K, V> kvMap = (ImmutableMap<K, V>) map; if (!kvMap.isPartialView()) { return kvMap; } } else if (map instanceof EnumMap) { EnumMap<?, ?> enumMap = (EnumMap<?, ?>) map; for (Map.Entry<?, ?> entry : enumMap.entrySet()) { checkEntryNotNull(entry.getKey(), entry.getValue()); } @SuppressWarnings("unchecked") // immutable collections are safe for covariant casts ImmutableMap<K, V> result = ImmutableEnumMap.asImmutable(new EnumMap(enumMap)); return result; } Entry<?, ?>[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); switch (entries.length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // all entries will be Entry<K, V>'s Entry<K, V> onlyEntry = (Entry<K, V>) entries[0]; return of(onlyEntry.getKey(), onlyEntry.getValue()); default: return new RegularImmutableMap<K, V>(entries); } } private static final Entry<?, ?>[] EMPTY_ENTRY_ARRAY = new Entry<?, ?>[0]; ImmutableMap() {} /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final V put(K k, V v) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final V remove(Object o) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the map unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override public final void clear() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean containsKey(@Nullable Object key) { return get(key) != null; } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } // Overriding to mark it Nullable @Override public abstract V get(@Nullable Object key); private transient ImmutableSet<Entry<K, V>> entrySet; /** * Returns an immutable set of the mappings in this map. The entries are in * the same order as the parameters used to build this map. */ @Override public ImmutableSet<Entry<K, V>> entrySet() { ImmutableSet<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract ImmutableSet<Entry<K, V>> createEntrySet(); private transient ImmutableSet<K> keySet; /** * Returns an immutable set of the keys in this map. These keys are in * the same order as the parameters used to build this map. */ @Override public ImmutableSet<K> keySet() { ImmutableSet<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } ImmutableSet<K> createKeySet() { return new ImmutableMapKeySet<K, V>(this); } private transient ImmutableCollection<V> values; /** * Returns an immutable collection of the values in this map. The values are * in the same order as the parameters used to build this map. */ @Override public ImmutableCollection<V> values() { ImmutableCollection<V> result = values; return (result == null) ? values = new ImmutableMapValues<K, V>(this) : result; } // cached so that this.multimapView().inverse() only computes inverse once private transient ImmutableSetMultimap<K, V> multimapView; /** * Returns a multimap view of the map. * * @since 14.0 */ @Beta public ImmutableSetMultimap<K, V> asMultimap() { ImmutableSetMultimap<K, V> result = multimapView; return (result == null) ? (multimapView = createMultimapView()) : result; } private ImmutableSetMultimap<K, V> createMultimapView() { ImmutableMap<K, ImmutableSet<V>> map = viewMapValuesAsSingletonSets(); return new ImmutableSetMultimap<K, V>(map, map.size(), null); } private ImmutableMap<K, ImmutableSet<V>> viewMapValuesAsSingletonSets() { return new MapViewOfValuesAsSingletonSets<K, V>(this); } private static final class MapViewOfValuesAsSingletonSets<K, V> extends ImmutableMap<K, ImmutableSet<V>> { private final ImmutableMap<K, V> delegate; MapViewOfValuesAsSingletonSets(ImmutableMap<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override public int size() { return delegate.size(); } @Override public boolean containsKey(@Nullable Object key) { return delegate.containsKey(key); } @Override public ImmutableSet<V> get(@Nullable Object key) { V outerValue = delegate.get(key); return (outerValue == null) ? null : ImmutableSet.of(outerValue); } @Override boolean isPartialView() { return false; } @Override ImmutableSet<Entry<K, ImmutableSet<V>>> createEntrySet() { return new ImmutableMapEntrySet<K, ImmutableSet<V>>() { @Override ImmutableMap<K, ImmutableSet<V>> map() { return MapViewOfValuesAsSingletonSets.this; } @Override public UnmodifiableIterator<Entry<K, ImmutableSet<V>>> iterator() { final Iterator<Entry<K, V>> backingIterator = delegate.entrySet().iterator(); return new UnmodifiableIterator<Entry<K, ImmutableSet<V>>>() { @Override public boolean hasNext() { return backingIterator.hasNext(); } @Override public Entry<K, ImmutableSet<V>> next() { final Entry<K, V> backingEntry = backingIterator.next(); return new AbstractMapEntry<K, ImmutableSet<V>>() { @Override public K getKey() { return backingEntry.getKey(); } @Override public ImmutableSet<V> getValue() { return ImmutableSet.of(backingEntry.getValue()); } }; } }; } }; } } @Override public boolean equals(@Nullable Object object) { return Maps.equalsImpl(this, object); } abstract boolean isPartialView(); @Override public int hashCode() { // not caching hash code since it could change if map values are mutable // in a way that modifies their hash codes return entrySet().hashCode(); } @Override public String toString() { return Maps.toStringImpl(this); } /** * Serialized type for all ImmutableMap instances. It captures the logical * contents and they are reconstructed using public factory methods. This * ensures that the implementation types remain as implementation details. */ static class SerializedForm implements Serializable { private final Object[] keys; private final Object[] values; SerializedForm(ImmutableMap<?, ?> map) { keys = new Object[map.size()]; values = new Object[map.size()]; int i = 0; for (Entry<?, ?> entry : map.entrySet()) { keys[i] = entry.getKey(); values[i] = entry.getValue(); i++; } } Object readResolve() { Builder<Object, Object> builder = new Builder<Object, Object>(); return createMap(builder); } Object createMap(Builder<Object, Object> builder) { for (int i = 0; i < keys.length; i++) { builder.put(keys[i], values[i]); } return builder.build(); } private static final long serialVersionUID = 0; } Object writeReplace() { return new SerializedForm(this); } }
Java
/* * 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.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * Factory and utilities pertaining to the {@code MapConstraint} interface. * * @see Constraints * @author Mike Bostock * @since 3.0 */ @Beta @GwtCompatible public final class MapConstraints { private MapConstraints() {} /** * Returns a constraint that verifies that neither the key nor the value is * null. If either is null, a {@link NullPointerException} is thrown. */ public static MapConstraint<Object, Object> notNull() { return NotNullMapConstraint.INSTANCE; } // enum singleton pattern private enum NotNullMapConstraint implements MapConstraint<Object, Object> { INSTANCE; @Override public void checkKeyValue(Object key, Object value) { checkNotNull(key); checkNotNull(value); } @Override public String toString() { return "Not null"; } } /** * Returns a constrained view of the specified map, using the specified * constraint. Any operations that add new mappings will call the provided * constraint. However, this method does not verify that existing mappings * satisfy the constraint. * * <p>The returned map is not serializable. * * @param map the map to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the specified map */ public static <K, V> Map<K, V> constrainedMap( Map<K, V> map, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedMap<K, V>(map, constraint); } /** * Returns a constrained view of the specified multimap, using the specified * constraint. Any operations that add new mappings will call the provided * constraint. However, this method does not verify that existing mappings * satisfy the constraint. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are not * constrained. * * <p>The returned multimap is not serializable. * * @param multimap the multimap to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the multimap */ public static <K, V> Multimap<K, V> constrainedMultimap( Multimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedMultimap<K, V>(multimap, constraint); } /** * Returns a constrained view of the specified list multimap, using the * specified constraint. Any operations that add new mappings will call the * provided constraint. However, this method does not verify that existing * mappings satisfy the constraint. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are not * constrained. * * <p>The returned multimap is not serializable. * * @param multimap the multimap to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the specified multimap */ public static <K, V> ListMultimap<K, V> constrainedListMultimap( ListMultimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedListMultimap<K, V>(multimap, constraint); } /** * Returns a constrained view of the specified set multimap, using the * specified constraint. Any operations that add new mappings will call the * provided constraint. However, this method does not verify that existing * mappings satisfy the constraint. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are not * constrained. * <p>The returned multimap is not serializable. * * @param multimap the multimap to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the specified multimap */ public static <K, V> SetMultimap<K, V> constrainedSetMultimap( SetMultimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedSetMultimap<K, V>(multimap, constraint); } /** * Returns a constrained view of the specified sorted-set multimap, using the * specified constraint. Any operations that add new mappings will call the * provided constraint. However, this method does not verify that existing * mappings satisfy the constraint. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and * {@link Multimap#replaceValues} methods return collections that are not * constrained. * <p>The returned multimap is not serializable. * * @param multimap the multimap to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the specified multimap */ public static <K, V> SortedSetMultimap<K, V> constrainedSortedSetMultimap( SortedSetMultimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedSortedSetMultimap<K, V>(multimap, constraint); } /** * Returns a constrained view of the specified entry, using the specified * constraint. The {@link Entry#setValue} operation will be verified with the * constraint. * * @param entry the entry to constrain * @param constraint the constraint for the entry * @return a constrained view of the specified entry */ private static <K, V> Entry<K, V> constrainedEntry( final Entry<K, V> entry, final MapConstraint<? super K, ? super V> constraint) { checkNotNull(entry); checkNotNull(constraint); return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return entry; } @Override public V setValue(V value) { constraint.checkKeyValue(getKey(), value); return entry.setValue(value); } }; } /** * Returns a constrained view of the specified {@code asMap} entry, using the * specified constraint. The {@link Entry#setValue} operation will be verified * with the constraint, and the collection returned by {@link Entry#getValue} * will be similarly constrained. * * @param entry the {@code asMap} entry to constrain * @param constraint the constraint for the entry * @return a constrained view of the specified entry */ private static <K, V> Entry<K, Collection<V>> constrainedAsMapEntry( final Entry<K, Collection<V>> entry, final MapConstraint<? super K, ? super V> constraint) { checkNotNull(entry); checkNotNull(constraint); return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return Constraints.constrainedTypePreservingCollection( entry.getValue(), new Constraint<V>() { @Override public V checkElement(V value) { constraint.checkKeyValue(getKey(), value); return value; } }); } }; } /** * Returns a constrained view of the specified set of {@code asMap} entries, * using the specified constraint. The {@link Entry#setValue} operation will * be verified with the constraint, and the collection returned by {@link * Entry#getValue} will be similarly constrained. The {@code add} and {@code * addAll} operations simply forward to the underlying set, which throws an * {@link UnsupportedOperationException} per the multimap specification. * * @param entries the entries to constrain * @param constraint the constraint for the entries * @return a constrained view of the entries */ private static <K, V> Set<Entry<K, Collection<V>>> constrainedAsMapEntries( Set<Entry<K, Collection<V>>> entries, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedAsMapEntries<K, V>(entries, constraint); } /** * Returns a constrained view of the specified collection (or set) of entries, * using the specified constraint. The {@link Entry#setValue} operation will * be verified with the constraint, along with add operations on the returned * collection. The {@code add} and {@code addAll} operations simply forward to * the underlying collection, which throws an {@link * UnsupportedOperationException} per the map and multimap specification. * * @param entries the entries to constrain * @param constraint the constraint for the entries * @return a constrained view of the specified entries */ private static <K, V> Collection<Entry<K, V>> constrainedEntries( Collection<Entry<K, V>> entries, MapConstraint<? super K, ? super V> constraint) { if (entries instanceof Set) { return constrainedEntrySet((Set<Entry<K, V>>) entries, constraint); } return new ConstrainedEntries<K, V>(entries, constraint); } /** * Returns a constrained view of the specified set of entries, using the * specified constraint. The {@link Entry#setValue} operation will be verified * with the constraint, along with add operations on the returned set. The * {@code add} and {@code addAll} operations simply forward to the underlying * set, which throws an {@link UnsupportedOperationException} per the map and * multimap specification. * * <p>The returned multimap is not serializable. * * @param entries the entries to constrain * @param constraint the constraint for the entries * @return a constrained view of the specified entries */ private static <K, V> Set<Entry<K, V>> constrainedEntrySet( Set<Entry<K, V>> entries, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedEntrySet<K, V>(entries, constraint); } /** @see MapConstraints#constrainedMap */ static class ConstrainedMap<K, V> extends ForwardingMap<K, V> { private final Map<K, V> delegate; final MapConstraint<? super K, ? super V> constraint; private transient Set<Entry<K, V>> entrySet; ConstrainedMap( Map<K, V> delegate, MapConstraint<? super K, ? super V> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected Map<K, V> delegate() { return delegate; } @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; if (result == null) { entrySet = result = constrainedEntrySet(delegate.entrySet(), constraint); } return result; } @Override public V put(K key, V value) { constraint.checkKeyValue(key, value); return delegate.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> map) { delegate.putAll(checkMap(map, constraint)); } } /** * Returns a constrained view of the specified bimap, using the specified * constraint. Any operations that modify the bimap will have the associated * keys and values verified with the constraint. * * <p>The returned bimap is not serializable. * * @param map the bimap to constrain * @param constraint the constraint that validates added entries * @return a constrained view of the specified bimap */ public static <K, V> BiMap<K, V> constrainedBiMap( BiMap<K, V> map, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedBiMap<K, V>(map, null, constraint); } /** @see MapConstraints#constrainedBiMap */ private static class ConstrainedBiMap<K, V> extends ConstrainedMap<K, V> implements BiMap<K, V> { /* * We could switch to racy single-check lazy init and remove volatile, but * there's a downside. That's because this field is also written in the * constructor. Without volatile, the constructor's write of the existing * inverse BiMap could occur after inverse()'s read of the field's initial * null value, leading inverse() to overwrite the existing inverse with a * doubly indirect version. This wouldn't be catastrophic, but it's * something to keep in mind if we make the change. * * Note that UnmodifiableBiMap *does* use racy single-check lazy init. * TODO(cpovirk): pick one and standardize */ volatile BiMap<V, K> inverse; ConstrainedBiMap(BiMap<K, V> delegate, @Nullable BiMap<V, K> inverse, MapConstraint<? super K, ? super V> constraint) { super(delegate, constraint); this.inverse = inverse; } @Override protected BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public V forcePut(K key, V value) { constraint.checkKeyValue(key, value); return delegate().forcePut(key, value); } @Override public BiMap<V, K> inverse() { if (inverse == null) { inverse = new ConstrainedBiMap<V, K>(delegate().inverse(), this, new InverseConstraint<V, K>(constraint)); } return inverse; } @Override public Set<V> values() { return delegate().values(); } } /** @see MapConstraints#constrainedBiMap */ private static class InverseConstraint<K, V> implements MapConstraint<K, V> { final MapConstraint<? super V, ? super K> constraint; public InverseConstraint(MapConstraint<? super V, ? super K> constraint) { this.constraint = checkNotNull(constraint); } @Override public void checkKeyValue(K key, V value) { constraint.checkKeyValue(value, key); } } /** @see MapConstraints#constrainedMultimap */ private static class ConstrainedMultimap<K, V> extends ForwardingMultimap<K, V> implements Serializable { final MapConstraint<? super K, ? super V> constraint; final Multimap<K, V> delegate; transient Collection<Entry<K, V>> entries; transient Map<K, Collection<V>> asMap; public ConstrainedMultimap(Multimap<K, V> delegate, MapConstraint<? super K, ? super V> constraint) { this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override protected Multimap<K, V> delegate() { return delegate; } @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = asMap; if (result == null) { final Map<K, Collection<V>> asMapDelegate = delegate.asMap(); asMap = result = new ForwardingMap<K, Collection<V>>() { Set<Entry<K, Collection<V>>> entrySet; Collection<Collection<V>> values; @Override protected Map<K, Collection<V>> delegate() { return asMapDelegate; } @Override public Set<Entry<K, Collection<V>>> entrySet() { Set<Entry<K, Collection<V>>> result = entrySet; if (result == null) { entrySet = result = constrainedAsMapEntries( asMapDelegate.entrySet(), constraint); } return result; } @SuppressWarnings("unchecked") @Override public Collection<V> get(Object key) { try { Collection<V> collection = ConstrainedMultimap.this.get((K) key); return collection.isEmpty() ? null : collection; } catch (ClassCastException e) { return null; // key wasn't a K } } @Override public Collection<Collection<V>> values() { Collection<Collection<V>> result = values; if (result == null) { values = result = new ConstrainedAsMapValues<K, V>( delegate().values(), entrySet()); } return result; } @Override public boolean containsValue(Object o) { return values().contains(o); } }; } return result; } @Override public Collection<Entry<K, V>> entries() { Collection<Entry<K, V>> result = entries; if (result == null) { entries = result = constrainedEntries(delegate.entries(), constraint); } return result; } @Override public Collection<V> get(final K key) { return Constraints.constrainedTypePreservingCollection( delegate.get(key), new Constraint<V>() { @Override public V checkElement(V value) { constraint.checkKeyValue(key, value); return value; } }); } @Override public boolean put(K key, V value) { constraint.checkKeyValue(key, value); return delegate.put(key, value); } @Override public boolean putAll(K key, Iterable<? extends V> values) { return delegate.putAll(key, checkValues(key, values, constraint)); } @Override public boolean putAll( Multimap<? extends K, ? extends V> multimap) { boolean changed = false; for (Entry<? extends K, ? extends V> entry : multimap.entries()) { changed |= put(entry.getKey(), entry.getValue()); } return changed; } @Override public Collection<V> replaceValues( K key, Iterable<? extends V> values) { return delegate.replaceValues(key, checkValues(key, values, constraint)); } } /** @see ConstrainedMultimap#asMap */ private static class ConstrainedAsMapValues<K, V> extends ForwardingCollection<Collection<V>> { final Collection<Collection<V>> delegate; final Set<Entry<K, Collection<V>>> entrySet; /** * @param entrySet map entries, linking each key with its corresponding * values, that already enforce the constraint */ ConstrainedAsMapValues(Collection<Collection<V>> delegate, Set<Entry<K, Collection<V>>> entrySet) { this.delegate = delegate; this.entrySet = entrySet; } @Override protected Collection<Collection<V>> delegate() { return delegate; } @Override public Iterator<Collection<V>> iterator() { final Iterator<Entry<K, Collection<V>>> iterator = entrySet.iterator(); return new Iterator<Collection<V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Collection<V> next() { return iterator.next().getValue(); } @Override public void remove() { iterator.remove(); } }; } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return standardContains(o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean remove(Object o) { return standardRemove(o); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** @see MapConstraints#constrainedEntries */ private static class ConstrainedEntries<K, V> extends ForwardingCollection<Entry<K, V>> { final MapConstraint<? super K, ? super V> constraint; final Collection<Entry<K, V>> entries; ConstrainedEntries(Collection<Entry<K, V>> entries, MapConstraint<? super K, ? super V> constraint) { this.entries = entries; this.constraint = constraint; } @Override protected Collection<Entry<K, V>> delegate() { return entries; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = entries.iterator(); return new ForwardingIterator<Entry<K, V>>() { @Override public Entry<K, V> next() { return constrainedEntry(iterator.next(), constraint); } @Override protected Iterator<Entry<K, V>> delegate() { return iterator; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean remove(Object o) { return Maps.removeEntryImpl(delegate(), o); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** @see MapConstraints#constrainedEntrySet */ static class ConstrainedEntrySet<K, V> extends ConstrainedEntries<K, V> implements Set<Entry<K, V>> { ConstrainedEntrySet(Set<Entry<K, V>> entries, MapConstraint<? super K, ? super V> constraint) { super(entries, constraint); } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public boolean equals(@Nullable Object object) { return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } } /** @see MapConstraints#constrainedAsMapEntries */ static class ConstrainedAsMapEntries<K, V> extends ForwardingSet<Entry<K, Collection<V>>> { private final MapConstraint<? super K, ? super V> constraint; private final Set<Entry<K, Collection<V>>> entries; ConstrainedAsMapEntries(Set<Entry<K, Collection<V>>> entries, MapConstraint<? super K, ? super V> constraint) { this.entries = entries; this.constraint = constraint; } @Override protected Set<Entry<K, Collection<V>>> delegate() { return entries; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { final Iterator<Entry<K, Collection<V>>> iterator = entries.iterator(); return new ForwardingIterator<Entry<K, Collection<V>>>() { @Override public Entry<K, Collection<V>> next() { return constrainedAsMapEntry(iterator.next(), constraint); } @Override protected Iterator<Entry<K, Collection<V>>> delegate() { return iterator; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean equals(@Nullable Object object) { return standardEquals(object); } @Override public int hashCode() { return standardHashCode(); } @Override public boolean remove(Object o) { return Maps.removeEntryImpl(delegate(), o); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } private static class ConstrainedListMultimap<K, V> extends ConstrainedMultimap<K, V> implements ListMultimap<K, V> { ConstrainedListMultimap(ListMultimap<K, V> delegate, MapConstraint<? super K, ? super V> constraint) { super(delegate, constraint); } @Override public List<V> get(K key) { return (List<V>) super.get(key); } @Override public List<V> removeAll(Object key) { return (List<V>) super.removeAll(key); } @Override public List<V> replaceValues( K key, Iterable<? extends V> values) { return (List<V>) super.replaceValues(key, values); } } private static class ConstrainedSetMultimap<K, V> extends ConstrainedMultimap<K, V> implements SetMultimap<K, V> { ConstrainedSetMultimap(SetMultimap<K, V> delegate, MapConstraint<? super K, ? super V> constraint) { super(delegate, constraint); } @Override public Set<V> get(K key) { return (Set<V>) super.get(key); } @Override public Set<Map.Entry<K, V>> entries() { return (Set<Map.Entry<K, V>>) super.entries(); } @Override public Set<V> removeAll(Object key) { return (Set<V>) super.removeAll(key); } @Override public Set<V> replaceValues( K key, Iterable<? extends V> values) { return (Set<V>) super.replaceValues(key, values); } } private static class ConstrainedSortedSetMultimap<K, V> extends ConstrainedSetMultimap<K, V> implements SortedSetMultimap<K, V> { ConstrainedSortedSetMultimap(SortedSetMultimap<K, V> delegate, MapConstraint<? super K, ? super V> constraint) { super(delegate, constraint); } @Override public SortedSet<V> get(K key) { return (SortedSet<V>) super.get(key); } @Override public SortedSet<V> removeAll(Object key) { return (SortedSet<V>) super.removeAll(key); } @Override public SortedSet<V> replaceValues( K key, Iterable<? extends V> values) { return (SortedSet<V>) super.replaceValues(key, values); } @Override public Comparator<? super V> valueComparator() { return ((SortedSetMultimap<K, V>) delegate()).valueComparator(); } } private static <K, V> Collection<V> checkValues(K key, Iterable<? extends V> values, MapConstraint<? super K, ? super V> constraint) { Collection<V> copy = Lists.newArrayList(values); for (V value : copy) { constraint.checkKeyValue(key, value); } return copy; } private static <K, V> Map<K, V> checkMap(Map<? extends K, ? extends V> map, MapConstraint<? super K, ? super V> constraint) { Map<K, V> copy = new LinkedHashMap<K, V>(map); for (Entry<K, V> entry : copy.entrySet()) { constraint.checkKeyValue(entry.getKey(), entry.getValue()); } return copy; } }
Java
/* * Copyright (C) 2009 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.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Fixed-size {@link Table} implementation backed by a two-dimensional array. * * <p>The allowed row and column keys must be supplied when the table is * created. The table always contains a mapping for every row key / column pair. * The value corresponding to a given row and column is null unless another * value is provided. * * <p>The table's size is constant: the product of the number of supplied row * keys and the number of supplied column keys. The {@code remove} and {@code * clear} methods are not supported by the table or its views. The {@link * #erase} and {@link #eraseAll} methods may be used instead. * * <p>The ordering of the row and column keys provided when the table is * constructed determines the iteration ordering across rows and columns in the * table's views. None of the view iterators support {@link Iterator#remove}. * If the table is modified after an iterator is created, the iterator remains * valid. * * <p>This class requires less memory than the {@link HashBasedTable} and {@link * TreeBasedTable} implementations, except when the table is sparse. * * <p>Null row keys or column keys are not permitted. * * <p>This class provides methods involving the underlying array structure, * where the array indices correspond to the position of a row or column in the * lists of allowed keys and values. See the {@link #at}, {@link #set}, {@link * #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} methods for more * details. * * <p>Note that this implementation is not synchronized. If multiple threads * access the same cell of an {@code ArrayTable} concurrently and one of the * threads modifies its value, there is no guarantee that the new value will be * fully visible to the other threads. To guarantee that modifications are * visible, synchronize access to the table. Unlike other {@code Table} * implementations, synchronization is unnecessary between a thread that writes * to one cell and a thread that reads from another. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table"> * {@code Table}</a>. * * @author Jared Levy * @since 10.0 */ @Beta @GwtCompatible(emulated = true) public final class ArrayTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { /** * Creates an empty {@code ArrayTable}. * * @param rowKeys row keys that may be stored in the generated table * @param columnKeys column keys that may be stored in the generated table * @throws NullPointerException if any of the provided keys is null * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} * contains duplicates or is empty */ public static <R, C, V> ArrayTable<R, C, V> create( Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { return new ArrayTable<R, C, V>(rowKeys, columnKeys); } /* * TODO(jlevy): Add factory methods taking an Enum class, instead of an * iterable, to specify the allowed row keys and/or column keys. Note that * custom serialization logic is needed to support different enum sizes during * serialization and deserialization. */ /** * Creates an {@code ArrayTable} with the mappings in the provided table. * * <p>If {@code table} includes a mapping with row key {@code r} and a * separate mapping with column key {@code c}, the returned table contains a * mapping with row key {@code r} and column key {@code c}. If that row key / * column key pair in not in {@code table}, the pair maps to {@code null} in * the generated table. * * <p>The returned table allows subsequent {@code put} calls with the row keys * in {@code table.rowKeySet()} and the column keys in {@code * table.columnKeySet()}. Calling {@link #put} with other keys leads to an * {@code IllegalArgumentException}. * * <p>The ordering of {@code table.rowKeySet()} and {@code * table.columnKeySet()} determines the row and column iteration ordering of * the returned table. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if the provided table is empty */ public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, V> table) { return (table instanceof ArrayTable<?, ?, ?>) ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table) : new ArrayTable<R, C, V>(table); } private final ImmutableList<R> rowList; private final ImmutableList<C> columnList; // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex? private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final V[][] array; private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { this.rowList = ImmutableList.copyOf(rowKeys); this.columnList = ImmutableList.copyOf(columnKeys); checkArgument(!rowList.isEmpty()); checkArgument(!columnList.isEmpty()); /* * TODO(jlevy): Support empty rowKeys or columnKeys? If we do, when * columnKeys is empty but rowKeys isn't, the table is empty but * containsRow() can return true and rowKeySet() isn't empty. */ rowKeyToIndex = index(rowList); columnKeyToIndex = index(columnList); @SuppressWarnings("unchecked") V[][] tmpArray = (V[][]) new Object[rowList.size()][columnList.size()]; array = tmpArray; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); } private static <E> ImmutableMap<E, Integer> index(List<E> list) { ImmutableMap.Builder<E, Integer> columnBuilder = ImmutableMap.builder(); for (int i = 0; i < list.size(); i++) { columnBuilder.put(list.get(i), i); } return columnBuilder.build(); } private ArrayTable(Table<R, C, V> table) { this(table.rowKeySet(), table.columnKeySet()); putAll(table); } private ArrayTable(ArrayTable<R, C, V> table) { rowList = table.rowList; columnList = table.columnList; rowKeyToIndex = table.rowKeyToIndex; columnKeyToIndex = table.columnKeyToIndex; @SuppressWarnings("unchecked") V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()]; array = copy; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); } } private abstract static class ArrayMap<K, V> extends Maps.ImprovedAbstractMap<K, V> { private final ImmutableMap<K, Integer> keyIndex; private ArrayMap(ImmutableMap<K, Integer> keyIndex) { this.keyIndex = keyIndex; } @Override public Set<K> keySet() { return keyIndex.keySet(); } K getKey(int index) { return keyIndex.keySet().asList().get(index); } abstract String getKeyRole(); @Nullable abstract V getValue(int index); @Nullable abstract V setValue(int index, V newValue); @Override public int size() { return keyIndex.size(); } @Override public boolean isEmpty() { return keyIndex.isEmpty(); } @Override protected Set<Entry<K, V>> createEntrySet() { return new Maps.EntrySet<K, V>() { @Override Map<K, V> map() { return ArrayMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return new AbstractIndexedListIterator<Entry<K, V>>(size()) { @Override protected Entry<K, V> get(final int index) { return new AbstractMapEntry<K, V>() { @Override public K getKey() { return ArrayMap.this.getKey(index); } @Override public V getValue() { return ArrayMap.this.getValue(index); } @Override public V setValue(V value) { return ArrayMap.this.setValue(index, value); } }; } }; } }; } // TODO(user): consider an optimized values() implementation @Override public boolean containsKey(@Nullable Object key) { return keyIndex.containsKey(key); } @Override public V get(@Nullable Object key) { Integer index = keyIndex.get(key); if (index == null) { return null; } else { return getValue(index); } } @Override public V put(K key, V value) { Integer index = keyIndex.get(key); if (index == null) { throw new IllegalArgumentException( getKeyRole() + " " + key + " not in " + keyIndex.keySet()); } return setValue(index, value); } @Override public V remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } /** * Returns, as an immutable list, the row keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<R> rowKeyList() { return rowList; } /** * Returns, as an immutable list, the column keys provided when the table was * constructed, including those that are mapped to null values only. */ public ImmutableList<C> columnKeyList() { return columnList; } /** * Returns the value corresponding to the specified row and column indices. * The same value is returned by {@code * get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but * this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @return the value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V at(int rowIndex, int columnIndex) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); return array[rowIndex][columnIndex]; } /** * Associates {@code value} with the specified row and column indices. The * logic {@code * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} * has the same behavior, but this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @param value value to store in the table * @return the previous value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code * rowIndex} is greater then or equal to the number of allowed row keys, * or {@code columnIndex} is greater then or equal to the number of * allowed column keys */ public V set(int rowIndex, int columnIndex, @Nullable V value) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); V oldValue = array[rowIndex][columnIndex]; array[rowIndex][columnIndex] = value; return oldValue; } /** * Returns a two-dimensional array with the table contents. The row and column * indices correspond to the positions of the row and column in the iterables * provided during table construction. If the table lacks a mapping for a * given row and column, the corresponding array element is null. * * <p>Subsequent table changes will not modify the array, and vice versa. * * @param valueClass class of values stored in the returned array */ @GwtIncompatible("reflection") public V[][] toArray(Class<V> valueClass) { // Can change to use varargs in JDK 1.6 if we want @SuppressWarnings("unchecked") // TODO: safe? V[][] copy = (V[][]) Array.newInstance( valueClass, new int[] { rowList.size(), columnList.size() }); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } return copy; } /** * Not supported. Use {@link #eraseAll} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #eraseAll} */ @Override @Deprecated public void clear() { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with every pair of allowed row and column * keys. */ public void eraseAll() { for (V[] row : array) { Arrays.fill(row, null); } } /** * Returns {@code true} if the provided keys are among the keys provided when * the table was constructed. */ @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return containsRow(rowKey) && containsColumn(columnKey); } /** * Returns {@code true} if the provided column key is among the column keys * provided when the table was constructed. */ @Override public boolean containsColumn(@Nullable Object columnKey) { return columnKeyToIndex.containsKey(columnKey); } /** * Returns {@code true} if the provided row key is among the row keys * provided when the table was constructed. */ @Override public boolean containsRow(@Nullable Object rowKey) { return rowKeyToIndex.containsKey(rowKey); } @Override public boolean containsValue(@Nullable Object value) { for (V[] row : array) { for (V element : row) { if (Objects.equal(value, element)) { return true; } } } return false; } @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex); } /** * Always returns {@code false}. */ @Override public boolean isEmpty() { return false; } /** * {@inheritDoc} * * @throws IllegalArgumentException if {@code rowKey} is not in {@link * #rowKeySet()} or {@code columnKey} is not in {@link #columnKeySet()}. */ @Override public V put(R rowKey, C columnKey, @Nullable V value) { checkNotNull(rowKey); checkNotNull(columnKey); Integer rowIndex = rowKeyToIndex.get(rowKey); checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList); Integer columnIndex = columnKeyToIndex.get(columnKey); checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList); return set(rowIndex, columnIndex, value); } /* * TODO(jlevy): Consider creating a merge() method, similar to putAll() but * copying non-null values only. */ /** * {@inheritDoc} * * <p>If {@code table} is an {@code ArrayTable}, its null values will be * stored in this table, possibly replacing values that were previously * non-null. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if any of the provided table's row keys or * column keys is not in {@link #rowKeySet()} or {@link #columnKeySet()} */ @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { super.putAll(table); } /** * Not supported. Use {@link #erase} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #erase} */ @Override @Deprecated public V remove(Object rowKey, Object columnKey) { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with the specified keys, assuming both * keys are valid. If either key is null or isn't among the keys provided * during construction, this method has no effect. * * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when * both provided keys are valid. * * @param rowKey row key of mapping to be erased * @param columnKey column key of mapping to be erased * @return the value previously associated with the keys, or {@code null} if * no mapping existed for the keys */ public V erase(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); if (rowIndex == null || columnIndex == null) { return null; } return set(rowIndex, columnIndex, null); } // TODO(jlevy): Add eraseRow and eraseColumn methods? @Override public int size() { return rowList.size() * columnList.size(); } /** * Returns an unmodifiable set of all row key / column key / value * triplets. Changes to the table will update the returned set. * * <p>The returned set's iterator traverses the mappings with the first row * key, the mappings with the second row key, and so on. * * <p>The value in the returned cells may change if the table subsequently * changes. * * @return set of table cells consisting of row key / column key / value * triplets */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new AbstractIndexedListIterator<Cell<R, C, V>>(size()) { @Override protected Cell<R, C, V> get(final int index) { return new Tables.AbstractCell<R, C, V>() { final int rowIndex = index / columnList.size(); final int columnIndex = index % columnList.size(); @Override public R getRowKey() { return rowList.get(rowIndex); } @Override public C getColumnKey() { return columnList.get(columnIndex); } @Override public V getValue() { return at(rowIndex, columnIndex); } }; } }; } /** * Returns a view of all mappings that have the given column key. If the * column key isn't in {@link #columnKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map * associates the row key with the corresponding value in the table. Changes * to the returned map will update the underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ @Override public Map<R, V> column(C columnKey) { checkNotNull(columnKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (columnIndex == null) ? ImmutableMap.<R, V>of() : new Column(columnIndex); } private class Column extends ArrayMap<R, V> { final int columnIndex; Column(int columnIndex) { super(rowKeyToIndex); this.columnIndex = columnIndex; } @Override String getKeyRole() { return "Row"; } @Override V getValue(int index) { return at(index, columnIndex); } @Override V setValue(int index, V newValue) { return set(index, columnIndex, newValue); } } /** * Returns an immutable set of the valid column keys, including those that * are associated with null values only. * * @return immutable set of column keys */ @Override public ImmutableSet<C> columnKeySet() { return columnKeyToIndex.keySet(); } private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap map = columnMap; return (map == null) ? columnMap = new ColumnMap() : map; } private class ColumnMap extends ArrayMap<C, Map<R, V>> { private ColumnMap() { super(columnKeyToIndex); } @Override String getKeyRole() { return "Column"; } @Override Map<R, V> getValue(int index) { return new Column(index); } @Override Map<R, V> setValue(int index, Map<R, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<R, V> put(C key, Map<R, V> value) { throw new UnsupportedOperationException(); } } /** * Returns a view of all mappings that have the given row key. If the * row key isn't in {@link #rowKeySet()}, an empty immutable map is * returned. * * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned * map associates the column key with the corresponding value in the * table. Changes to the returned map will update the underlying table, and * vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ @Override public Map<C, V> row(R rowKey) { checkNotNull(rowKey); Integer rowIndex = rowKeyToIndex.get(rowKey); return (rowIndex == null) ? ImmutableMap.<C, V>of() : new Row(rowIndex); } private class Row extends ArrayMap<C, V> { final int rowIndex; Row(int rowIndex) { super(columnKeyToIndex); this.rowIndex = rowIndex; } @Override String getKeyRole() { return "Column"; } @Override V getValue(int index) { return at(rowIndex, index); } @Override V setValue(int index, V newValue) { return set(rowIndex, index, newValue); } } /** * Returns an immutable set of the valid row keys, including those that are * associated with null values only. * * @return immutable set of row keys */ @Override public ImmutableSet<R> rowKeySet() { return rowKeyToIndex.keySet(); } private transient RowMap rowMap; @Override public Map<R, Map<C, V>> rowMap() { RowMap map = rowMap; return (map == null) ? rowMap = new RowMap() : map; } private class RowMap extends ArrayMap<R, Map<C, V>> { private RowMap() { super(rowKeyToIndex); } @Override String getKeyRole() { return "Row"; } @Override Map<C, V> getValue(int index) { return new Row(index); } @Override Map<C, V> setValue(int index, Map<C, V> newValue) { throw new UnsupportedOperationException(); } @Override public Map<C, V> put(R key, Map<C, V> value) { throw new UnsupportedOperationException(); } } /** * Returns an unmodifiable collection of all values, which may contain * duplicates. Changes to the table will update the returned collection. * * <p>The returned collection's iterator traverses the values of the first row * key, the values of the second row key, and so on. * * @return collection of values */ @Override public Collection<V> values() { return super.values(); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 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 java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.common.annotations.GwtCompatible; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} * to work around build-system quirks. This annotation should be used * <b>only</b> in {@code com.google.common.collect}. */ @Documented @GwtCompatible @Retention(RUNTIME) @Target(FIELD) @interface GwtTransient { }
Java
/* * Copyright (C) 2012 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 java.util.AbstractMap; import java.util.Iterator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import javax.annotation.Nullable; /** * Skeletal implementation of {@link NavigableMap}. * * @author Louis Wasserman */ abstract class AbstractNavigableMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V> { @Override @Nullable public abstract V get(@Nullable Object key); @Override @Nullable public Entry<K, V> firstEntry() { return Iterators.getNext(entryIterator(), null); } @Override @Nullable public Entry<K, V> lastEntry() { return Iterators.getNext(descendingEntryIterator(), null); } @Override @Nullable public Entry<K, V> pollFirstEntry() { return Iterators.pollNext(entryIterator()); } @Override @Nullable public Entry<K, V> pollLastEntry() { return Iterators.pollNext(descendingEntryIterator()); } @Override public K firstKey() { Entry<K, V> entry = firstEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override public K lastKey() { Entry<K, V> entry = lastEntry(); if (entry == null) { throw new NoSuchElementException(); } else { return entry.getKey(); } } @Override @Nullable public Entry<K, V> lowerEntry(K key) { return headMap(key, false).lastEntry(); } @Override @Nullable public Entry<K, V> floorEntry(K key) { return headMap(key, true).lastEntry(); } @Override @Nullable public Entry<K, V> ceilingEntry(K key) { return tailMap(key, true).firstEntry(); } @Override @Nullable public Entry<K, V> higherEntry(K key) { return tailMap(key, false).firstEntry(); } @Override public K lowerKey(K key) { return Maps.keyOrNull(lowerEntry(key)); } @Override public K floorKey(K key) { return Maps.keyOrNull(floorEntry(key)); } @Override public K ceilingKey(K key) { return Maps.keyOrNull(ceilingEntry(key)); } @Override public K higherKey(K key) { return Maps.keyOrNull(higherEntry(key)); } abstract Iterator<Entry<K, V>> entryIterator(); abstract Iterator<Entry<K, V>> descendingEntryIterator(); @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableSet<K> navigableKeySet() { return new Maps.NavigableKeySet<K, V>(this); } @Override public Set<K> keySet() { return navigableKeySet(); } @Override public abstract int size(); @Override public Set<Entry<K, V>> entrySet() { return new Maps.EntrySet<K, V>() { @Override Map<K, V> map() { return AbstractNavigableMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } }; } @Override public NavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } @Override public NavigableMap<K, V> descendingMap() { return new DescendingMap(); } private final class DescendingMap extends Maps.DescendingMap<K, V> { @Override NavigableMap<K, V> forward() { return AbstractNavigableMap.this; } @Override Iterator<Entry<K, V>> entryIterator() { return descendingEntryIterator(); } } }
Java
/* * 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 com.google.common.annotations.GwtCompatible; import java.util.Map; import javax.annotation.Nullable; /** * An object representing the differences between two maps. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface MapDifference<K, V> { /** * Returns {@code true} if there are no differences between the two maps; * that is, if the maps are equal. */ boolean areEqual(); /** * Returns an unmodifiable map containing the entries from the left map whose * keys are not present in the right map. */ Map<K, V> entriesOnlyOnLeft(); /** * Returns an unmodifiable map containing the entries from the right map whose * keys are not present in the left map. */ Map<K, V> entriesOnlyOnRight(); /** * Returns an unmodifiable map containing the entries that appear in both * maps; that is, the intersection of the two maps. */ Map<K, V> entriesInCommon(); /** * Returns an unmodifiable map describing keys that appear in both maps, but * with different values. */ Map<K, ValueDifference<V>> entriesDiffering(); /** * Compares the specified object with this instance for equality. Returns * {@code true} if the given object is also a {@code MapDifference} and the * values returned by the {@link #entriesOnlyOnLeft()}, {@link * #entriesOnlyOnRight()}, {@link #entriesInCommon()} and {@link * #entriesDiffering()} of the two instances are equal. */ @Override boolean equals(@Nullable Object object); /** * Returns the hash code for this instance. This is defined as the hash code * of <pre> {@code * * Arrays.asList(entriesOnlyOnLeft(), entriesOnlyOnRight(), * entriesInCommon(), entriesDiffering())}</pre> */ @Override int hashCode(); /** * A difference between the mappings from two maps with the same key. The * {@link #leftValue} and {@link #rightValue} are not equal, and one but not * both of them may be null. * * @since 2.0 (imported from Google Collections Library) */ interface ValueDifference<V> { /** * Returns the value from the left map (possibly null). */ V leftValue(); /** * Returns the value from the right map (possibly null). */ V rightValue(); /** * Two instances are considered equal if their {@link #leftValue()} * values are equal and their {@link #rightValue()} values are also equal. */ @Override boolean equals(@Nullable Object other); /** * The hash code equals the value * {@code Arrays.asList(leftValue(), rightValue()).hashCode()}. */ @Override int hashCode(); } }
Java
/* * Copyright (C) 2009 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.Objects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.MapMakerInternalMap.Strength.SOFT; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Ascii; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.google.common.base.Ticker; import com.google.common.collect.MapMakerInternalMap.Strength; import java.io.Serializable; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractMap; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * <p>A builder of {@link ConcurrentMap} instances having any combination of the following features: * * <ul> * <li>keys or values automatically wrapped in {@linkplain WeakReference weak} or {@linkplain * SoftReference soft} references * <li>notification of evicted (or otherwise removed) entries * <li>on-demand computation of values for keys not already present * </ul> * * <p>Usage example: <pre> {@code * * ConcurrentMap<Request, Stopwatch> timers = new MapMaker() * .concurrencyLevel(4) * .weakKeys() * .makeMap();}</pre> * * <p>These features are all optional; {@code new MapMaker().makeMap()} returns a valid concurrent * map that behaves similarly to a {@link ConcurrentHashMap}. * * <p>The returned map is implemented as a hash table with similar performance characteristics to * {@link ConcurrentHashMap}. It supports all optional operations of the {@code ConcurrentMap} * interface. It does not permit null keys or values. * * <p><b>Note:</b> by default, the returned map uses equality comparisons (the {@link Object#equals * equals} method) to determine equality for keys or values. However, if {@link #weakKeys} was * specified, the map uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link * #weakValues} or {@link #softValues} was specified, the map uses identity comparisons for values. * * <p>The view collections of the returned map have <i>weakly consistent iterators</i>. This means * that they are safe for concurrent use, but if other threads modify the map after the iterator is * created, it is undefined which of these changes, if any, are reflected in that iterator. These * iterators never throw {@link ConcurrentModificationException}. * * <p>If {@link #weakKeys}, {@link #weakValues}, or {@link #softValues} are requested, it is * possible for a key or value present in the map to be reclaimed by the garbage collector. Entries * with reclaimed keys or values may be removed from the map on each map modification or on * occasional map accesses; such entries may be counted by {@link Map#size}, but will never be * visible to read or write operations. A partially-reclaimed entry is never exposed to the user. * Any {@link java.util.Map.Entry} instance retrieved from the map's * {@linkplain Map#entrySet entry set} is a snapshot of that entry's state at the time of * retrieval; such entries do, however, support {@link java.util.Map.Entry#setValue}, which simply * calls {@link Map#put} on the entry's key. * * <p>The maps produced by {@code MapMaker} are serializable, and the deserialized maps retain all * the configuration properties of the original map. During deserialization, if the original map had * used soft or weak references, the entries are reconstructed as they were, but it's not unlikely * they'll be quickly garbage-collected before they are ever accessed. * * <p>{@code new MapMaker().weakKeys().makeMap()} is a recommended replacement for {@link * java.util.WeakHashMap}, but note that it compares keys using object identity whereas {@code * WeakHashMap} uses {@link Object#equals}. * * @author Bob Lee * @author Charles Fry * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class MapMaker extends GenericMapMaker<Object, Object> { private static final int DEFAULT_INITIAL_CAPACITY = 16; private static final int DEFAULT_CONCURRENCY_LEVEL = 4; private static final int DEFAULT_EXPIRATION_NANOS = 0; static final int UNSET_INT = -1; // TODO(kevinb): dispense with this after benchmarking boolean useCustomMap; int initialCapacity = UNSET_INT; int concurrencyLevel = UNSET_INT; int maximumSize = UNSET_INT; Strength keyStrength; Strength valueStrength; long expireAfterWriteNanos = UNSET_INT; long expireAfterAccessNanos = UNSET_INT; RemovalCause nullRemovalCause; Equivalence<Object> keyEquivalence; Ticker ticker; /** * Constructs a new {@code MapMaker} instance with default settings, including strong keys, strong * values, and no automatic eviction of any kind. */ public MapMaker() {} /** * Sets a custom {@code Equivalence} strategy for comparing keys. * * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when {@link * #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this is * used is in {@link Interners.WeakInterner}. */ @GwtIncompatible("To be supported") @Override MapMaker keyEquivalence(Equivalence<Object> equivalence) { checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); keyEquivalence = checkNotNull(equivalence); this.useCustomMap = true; return this; } Equivalence<Object> getKeyEquivalence() { return firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence()); } /** * Sets the minimum total size for the internal hash tables. For example, if the initial capacity * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each * having a hash table of size eight. Providing a large enough estimate at construction time * avoids the need for expensive resizing operations later, but setting this value unnecessarily * high wastes memory. * * @throws IllegalArgumentException if {@code initialCapacity} is negative * @throws IllegalStateException if an initial capacity was already set */ @Override public MapMaker initialCapacity(int initialCapacity) { checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s", this.initialCapacity); checkArgument(initialCapacity >= 0); this.initialCapacity = initialCapacity; return this; } int getInitialCapacity() { return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity; } /** * Specifies the maximum number of entries the map may contain. Note that the map <b>may evict an * entry before this limit is exceeded</b>. As the map size grows close to the maximum, the map * evicts entries that are less likely to be used again. For example, the map may evict an entry * because it hasn't been used recently or very often. * * <p>When {@code size} is zero, elements can be successfully added to the map, but are evicted * immediately. This has the same effect as invoking {@link #expireAfterWrite * expireAfterWrite}{@code (0, unit)} or {@link #expireAfterAccess expireAfterAccess}{@code (0, * unit)}. It can be useful in testing, or to disable caching temporarily without a code change. * * <p>Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}. * * @param size the maximum size of the map * @throws IllegalArgumentException if {@code size} is negative * @throws IllegalStateException if a maximum size was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #maximumSize} being * replaced by {@link com.google.common.cache.CacheBuilder#maximumSize}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @Override MapMaker maximumSize(int size) { checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize); checkArgument(size >= 0, "maximum size must not be negative"); this.maximumSize = size; this.useCustomMap = true; if (maximumSize == 0) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.SIZE; } return this; } /** * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The * table is internally partitioned to try to permit the indicated number of concurrent updates * without contention. Because assignment of entries to these partitions is not necessarily * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to * accommodate as many threads as will ever concurrently modify the table. Using a significantly * higher value than you need can waste space and time, and a significantly lower value can lead * to thread contention. But overestimates and underestimates within an order of magnitude do not * usually have much noticeable impact. A value of one permits only one thread to modify the map * at a time, but since read operations can proceed concurrently, this still yields higher * concurrency than full synchronization. Defaults to 4. * * <p><b>Note:</b> Prior to Guava release 9.0, the default was 16. It is possible the default will * change again in the future. If you care about this value, you should always choose it * explicitly. * * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive * @throws IllegalStateException if a concurrency level was already set */ @Override public MapMaker concurrencyLevel(int concurrencyLevel) { checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; } int getConcurrencyLevel() { return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; } /** * Specifies that each key (not value) stored in the map should be wrapped in a {@link * WeakReference} (by default, strong references are used). * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of keys, which is a technical violation of the {@link Map} * specification, and may not be what you expect. * * @throws IllegalStateException if the key strength was already set * @see WeakReference */ @GwtIncompatible("java.lang.ref.WeakReference") @Override public MapMaker weakKeys() { return setKeyStrength(Strength.WEAK); } MapMaker setKeyStrength(Strength strength) { checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); keyStrength = checkNotNull(strength); checkArgument(keyStrength != SOFT, "Soft keys are not supported"); if (strength != Strength.STRONG) { // STRONG could be used during deserialization. useCustomMap = true; } return this; } Strength getKeyStrength() { return firstNonNull(keyStrength, Strength.STRONG); } /** * Specifies that each value (not key) stored in the map should be wrapped in a * {@link WeakReference} (by default, strong references are used). * * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor * candidate for caching; consider {@link #softValues} instead. * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of values. This technically violates the specifications of * the methods {@link Map#containsValue containsValue}, * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you * expect. * * @throws IllegalStateException if the value strength was already set * @see WeakReference */ @GwtIncompatible("java.lang.ref.WeakReference") @Override public MapMaker weakValues() { return setValueStrength(Strength.WEAK); } /** * Specifies that each value (not key) stored in the map should be wrapped in a * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory * demand. * * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain * #maximumSize maximum size} instead of using soft references. You should only use this method if * you are well familiar with the practical consequences of soft references. * * <p><b>Warning:</b> when this method is used, the resulting map will use identity ({@code ==}) * comparison to determine equality of values. This technically violates the specifications of * the methods {@link Map#containsValue containsValue}, * {@link ConcurrentMap#remove(Object, Object) remove(Object, Object)} and * {@link ConcurrentMap#replace(Object, Object, Object) replace(K, V, V)}, and may not be what you * expect. * * @throws IllegalStateException if the value strength was already set * @see SoftReference * @deprecated Caching functionality in {@code MapMaker} has been moved to {@link * com.google.common.cache.CacheBuilder}, with {@link #softValues} being replaced by {@link * com.google.common.cache.CacheBuilder#softValues}. Note that {@code CacheBuilder} is simply * an enhanced API for an implementation which was branched from {@code MapMaker}. <b>This * method is scheduled for deletion in September 2014.</b> */ @Deprecated @GwtIncompatible("java.lang.ref.SoftReference") @Override public MapMaker softValues() { return setValueStrength(Strength.SOFT); } MapMaker setValueStrength(Strength strength) { checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = checkNotNull(strength); if (strength != Strength.STRONG) { // STRONG could be used during deserialization. useCustomMap = true; } return this; } Strength getValueStrength() { return firstNonNull(valueStrength, Strength.STRONG); } /** * Specifies that each entry should be automatically removed from the map once a fixed duration * has elapsed after the entry's creation, or the most recent replacement of its value. * * <p>When {@code duration} is zero, elements can be successfully added to the map, but are * evicted immediately. This has a very similar effect to invoking {@link #maximumSize * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without * a code change. * * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or * write operations. Expired entries are currently cleaned up during write operations, or during * occasional read operations in the absense of writes; though this behavior may change in the * future. * * @param duration the length of time after an entry is created that it should be automatically * removed * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if the time to live or time to idle was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterWrite} being * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterWrite}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @Override MapMaker expireAfterWrite(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterWriteNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; } private void checkExpiration(long duration, TimeUnit unit) { checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", expireAfterWriteNanos); checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", expireAfterAccessNanos); checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); } long getExpireAfterWriteNanos() { return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; } /** * Specifies that each entry should be automatically removed from the map once a fixed duration * has elapsed after the entry's last read or write access. * * <p>When {@code duration} is zero, elements can be successfully added to the map, but are * evicted immediately. This has a very similar effect to invoking {@link #maximumSize * maximumSize}{@code (0)}. It can be useful in testing, or to disable caching temporarily without * a code change. * * <p>Expired entries may be counted by {@link Map#size}, but will never be visible to read or * write operations. Expired entries are currently cleaned up during write operations, or during * occasional read operations in the absense of writes; though this behavior may change in the * future. * * @param duration the length of time after an entry is last accessed that it should be * automatically removed * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if the time to idle or time to live was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #expireAfterAccess} being * replaced by {@link com.google.common.cache.CacheBuilder#expireAfterAccess}. Note that * {@code CacheBuilder} is simply an enhanced API for an implementation which was branched * from {@code MapMaker}. */ @Deprecated @GwtIncompatible("To be supported") @Override MapMaker expireAfterAccess(long duration, TimeUnit unit) { checkExpiration(duration, unit); this.expireAfterAccessNanos = unit.toNanos(duration); if (duration == 0 && this.nullRemovalCause == null) { // SIZE trumps EXPIRED this.nullRemovalCause = RemovalCause.EXPIRED; } useCustomMap = true; return this; } long getExpireAfterAccessNanos() { return (expireAfterAccessNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; } Ticker getTicker() { return firstNonNull(ticker, Ticker.systemTicker()); } /** * Specifies a listener instance, which all maps built using this {@code MapMaker} will notify * each time an entry is removed from the map by any means. * * <p>Each map built by this map maker after this method is called invokes the supplied listener * after removing an element for any reason (see removal causes in {@link RemovalCause}). It will * invoke the listener during invocations of any of that map's public methods (even read-only * methods). * * <p><b>Important note:</b> Instead of returning <i>this</i> as a {@code MapMaker} instance, * this method returns {@code GenericMapMaker<K, V>}. From this point on, either the original * reference or the returned reference may be used to complete configuration and build the map, * but only the "generic" one is type-safe. That is, it will properly prevent you from building * maps whose key or value types are incompatible with the types accepted by the listener already * provided; the {@code MapMaker} type cannot do this. For best results, simply use the standard * method-chaining idiom, as illustrated in the documentation at top, configuring a {@code * MapMaker} and building your {@link Map} all in a single statement. * * <p><b>Warning:</b> if you ignore the above advice, and use this {@code MapMaker} to build a map * or cache whose key or value type is incompatible with the listener, you will likely experience * a {@link ClassCastException} at some <i>undefined</i> point in the future. * * @throws IllegalStateException if a removal listener was already set * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #removalListener} being * replaced by {@link com.google.common.cache.CacheBuilder#removalListener}. Note that {@code * CacheBuilder} is simply an enhanced API for an implementation which was branched from * {@code MapMaker}. */ @Deprecated @GwtIncompatible("To be supported") <K, V> GenericMapMaker<K, V> removalListener(RemovalListener<K, V> listener) { checkState(this.removalListener == null); // safely limiting the kinds of maps this can produce @SuppressWarnings("unchecked") GenericMapMaker<K, V> me = (GenericMapMaker<K, V>) this; me.removalListener = checkNotNull(listener); useCustomMap = true; return me; } /** * Builds a thread-safe map, without on-demand computation of values. This method does not alter * the state of this {@code MapMaker} instance, so it can be invoked again to create multiple * independent maps. * * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to * be performed atomically on the returned map. Additionally, {@code size} and {@code * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent * writes. * * @return a serializable concurrent map having the requested features */ @Override public <K, V> ConcurrentMap<K, V> makeMap() { if (!useCustomMap) { return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel()); } return (nullRemovalCause == null) ? new MapMakerInternalMap<K, V>(this) : new NullConcurrentMap<K, V>(this); } /** * Returns a MapMakerInternalMap for the benefit of internal callers that use features of * that class not exposed through ConcurrentMap. */ @Override @GwtIncompatible("MapMakerInternalMap") <K, V> MapMakerInternalMap<K, V> makeCustomMap() { return new MapMakerInternalMap<K, V>(this); } /** * Builds a map that supports atomic, on-demand computation of values. {@link Map#get} either * returns an already-computed value for the given key, atomically computes it using the supplied * function, or, if another thread is currently computing the value for this key, simply waits for * that thread to finish and returns its computed value. Note that the function may be executed * concurrently by multiple threads, but only for distinct keys. * * <p>New code should use {@link com.google.common.cache.CacheBuilder}, which supports * {@linkplain com.google.common.cache.CacheStats statistics} collection, introduces the * {@link com.google.common.cache.CacheLoader} interface for loading entries into the cache * (allowing checked exceptions to be thrown in the process), and more cleanly separates * computation from the cache's {@code Map} view. * * <p>If an entry's value has not finished computing yet, query methods besides {@code get} return * immediately as if an entry doesn't exist. In other words, an entry isn't externally visible * until the value's computation completes. * * <p>{@link Map#get} on the returned map will never return {@code null}. It may throw: * * <ul> * <li>{@link NullPointerException} if the key is null or the computing function returns a null * result * <li>{@link ComputationException} if an exception was thrown by the computing function. If that * exception is already of type {@link ComputationException} it is propagated directly; otherwise * it is wrapped. * </ul> * * <p><b>Note:</b> Callers of {@code get} <i>must</i> ensure that the key argument is of type * {@code K}. The {@code get} method accepts {@code Object}, so the key type is not checked at * compile time. Passing an object of a type other than {@code K} can result in that object being * unsafely passed to the computing function as type {@code K}, and unsafely stored in the map. * * <p>If {@link Map#put} is called before a computation completes, other threads waiting on the * computation will wake up and return the stored value. * * <p>This method does not alter the state of this {@code MapMaker} instance, so it can be invoked * again to create multiple independent maps. * * <p>Insertion, removal, update, and access operations on the returned map safely execute * concurrently by multiple threads. Iterators on the returned map are weakly consistent, * returning elements reflecting the state of the map at some point at or since the creation of * the iterator. They do not throw {@link ConcurrentModificationException}, and may proceed * concurrently with other operations. * * <p>The bulk operations {@code putAll}, {@code equals}, and {@code clear} are not guaranteed to * be performed atomically on the returned map. Additionally, {@code size} and {@code * containsValue} are implemented as bulk read operations, and thus may fail to observe concurrent * writes. * * @param computingFunction the function used to compute new values * @return a serializable concurrent map having the requested features * @deprecated Caching functionality in {@code MapMaker} has been moved to * {@link com.google.common.cache.CacheBuilder}, with {@link #makeComputingMap} being replaced * by {@link com.google.common.cache.CacheBuilder#build}. See the * <a href="http://code.google.com/p/guava-libraries/wiki/MapMakerMigration">MapMaker * Migration Guide</a> for more details. */ @Deprecated @Override <K, V> ConcurrentMap<K, V> makeComputingMap( Function<? super K, ? extends V> computingFunction) { return (nullRemovalCause == null) ? new MapMaker.ComputingMapAdapter<K, V>(this, computingFunction) : new NullComputingConcurrentMap<K, V>(this, computingFunction); } /** * Returns a string representation for this MapMaker instance. The exact form of the returned * string is not specificed. */ @Override public String toString() { Objects.ToStringHelper s = Objects.toStringHelper(this); if (initialCapacity != UNSET_INT) { s.add("initialCapacity", initialCapacity); } if (concurrencyLevel != UNSET_INT) { s.add("concurrencyLevel", concurrencyLevel); } if (maximumSize != UNSET_INT) { s.add("maximumSize", maximumSize); } if (expireAfterWriteNanos != UNSET_INT) { s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); } if (expireAfterAccessNanos != UNSET_INT) { s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); } if (keyStrength != null) { s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); } if (valueStrength != null) { s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); } if (keyEquivalence != null) { s.addValue("keyEquivalence"); } if (removalListener != null) { s.addValue("removalListener"); } return s.toString(); } /** * An object that can receive a notification when an entry is removed from a map. The removal * resulting in notification could have occured to an entry being manually removed or replaced, or * due to eviction resulting from timed expiration, exceeding a maximum size, or garbage * collection. * * <p>An instance may be called concurrently by multiple threads to process different entries. * Implementations of this interface should avoid performing blocking calls or synchronizing on * shared resources. * * @param <K> the most general type of keys this listener can listen for; for * example {@code Object} if any key is acceptable * @param <V> the most general type of values this listener can listen for; for * example {@code Object} if any key is acceptable */ interface RemovalListener<K, V> { /** * Notifies the listener that a removal occurred at some point in the past. */ void onRemoval(RemovalNotification<K, V> notification); } /** * A notification of the removal of a single entry. The key or value may be null if it was already * garbage collected. * * <p>Like other {@code Map.Entry} instances associated with MapMaker, this class holds strong * references to the key and value, regardless of the type of references the map may be using. */ static final class RemovalNotification<K, V> extends ImmutableEntry<K, V> { private static final long serialVersionUID = 0; private final RemovalCause cause; RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) { super(key, value); this.cause = cause; } /** * Returns the cause for which the entry was removed. */ public RemovalCause getCause() { return cause; } /** * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}). */ public boolean wasEvicted() { return cause.wasEvicted(); } } /** * The reason why an entry was removed. */ enum RemovalCause { /** * The entry was manually removed by the user. This can result from the user invoking * {@link Map#remove}, {@link ConcurrentMap#remove}, or {@link java.util.Iterator#remove}. */ EXPLICIT { @Override boolean wasEvicted() { return false; } }, /** * The entry itself was not actually removed, but its value was replaced by the user. This can * result from the user invoking {@link Map#put}, {@link Map#putAll}, * {@link ConcurrentMap#replace(Object, Object)}, or * {@link ConcurrentMap#replace(Object, Object, Object)}. */ REPLACED { @Override boolean wasEvicted() { return false; } }, /** * The entry was removed automatically because its key or value was garbage-collected. This can * occur when using {@link #softValues}, {@link #weakKeys}, or {@link #weakValues}. */ COLLECTED { @Override boolean wasEvicted() { return true; } }, /** * The entry's expiration timestamp has passed. This can occur when using {@link * #expireAfterWrite} or {@link #expireAfterAccess}. */ EXPIRED { @Override boolean wasEvicted() { return true; } }, /** * The entry was evicted due to size constraints. This can occur when using {@link * #maximumSize}. */ SIZE { @Override boolean wasEvicted() { return true; } }; /** * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither * {@link #EXPLICIT} nor {@link #REPLACED}). */ abstract boolean wasEvicted(); } /** A map that is always empty and evicts on insertion. */ static class NullConcurrentMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable { private static final long serialVersionUID = 0; private final RemovalListener<K, V> removalListener; private final RemovalCause removalCause; NullConcurrentMap(MapMaker mapMaker) { removalListener = mapMaker.getRemovalListener(); removalCause = mapMaker.nullRemovalCause; } // implements ConcurrentMap @Override public boolean containsKey(@Nullable Object key) { return false; } @Override public boolean containsValue(@Nullable Object value) { return false; } @Override public V get(@Nullable Object key) { return null; } void notifyRemoval(K key, V value) { RemovalNotification<K, V> notification = new RemovalNotification<K, V>(key, value, removalCause); removalListener.onRemoval(notification); } @Override public V put(K key, V value) { checkNotNull(key); checkNotNull(value); notifyRemoval(key, value); return null; } @Override public V putIfAbsent(K key, V value) { return put(key, value); } @Override public V remove(@Nullable Object key) { return null; } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { return false; } @Override public V replace(K key, V value) { checkNotNull(key); checkNotNull(value); return null; } @Override public boolean replace(K key, @Nullable V oldValue, V newValue) { checkNotNull(key); checkNotNull(newValue); return false; } @Override public Set<Entry<K, V>> entrySet() { return Collections.emptySet(); } } /** Computes on retrieval and evicts the result. */ static final class NullComputingConcurrentMap<K, V> extends NullConcurrentMap<K, V> { private static final long serialVersionUID = 0; final Function<? super K, ? extends V> computingFunction; NullComputingConcurrentMap( MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { super(mapMaker); this.computingFunction = checkNotNull(computingFunction); } @SuppressWarnings("unchecked") // unsafe, which is why Cache is preferred @Override public V get(Object k) { K key = (K) k; V value = compute(key); checkNotNull(value, computingFunction + " returned null for key " + key + "."); notifyRemoval(key, value); return value; } private V compute(K key) { checkNotNull(key); try { return computingFunction.apply(key); } catch (ComputationException e) { throw e; } catch (Throwable t) { throw new ComputationException(t); } } } /** * Overrides get() to compute on demand. Also throws an exception when {@code null} is returned * from a computation. */ /* * This might make more sense in ComputingConcurrentHashMap, but it causes a javac crash in some * cases there: http://code.google.com/p/guava-libraries/issues/detail?id=950 */ static final class ComputingMapAdapter<K, V> extends ComputingConcurrentHashMap<K, V> implements Serializable { private static final long serialVersionUID = 0; ComputingMapAdapter(MapMaker mapMaker, Function<? super K, ? extends V> computingFunction) { super(mapMaker, computingFunction); } @SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map @Override public V get(Object key) { V value; try { value = getOrCompute((K) key); } catch (ExecutionException e) { Throwable cause = e.getCause(); Throwables.propagateIfInstanceOf(cause, ComputationException.class); throw new ComputationException(cause); } if (value == null) { throw new NullPointerException(computingFunction + " returned null for key " + key + "."); } return value; } } }
Java
/* * Copyright (C) 2012 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 com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * An implementation of an immutable sorted map with one or more entries. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization final class RegularImmutableSortedMap<K, V> extends ImmutableSortedMap<K, V> { private final transient RegularImmutableSortedSet<K> keySet; private final transient ImmutableList<V> valueList; RegularImmutableSortedMap(RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList) { this.keySet = keySet; this.valueList = valueList; } RegularImmutableSortedMap( RegularImmutableSortedSet<K> keySet, ImmutableList<V> valueList, ImmutableSortedMap<K, V> descendingMap) { super(descendingMap); this.keySet = keySet; this.valueList = valueList; } @Override ImmutableSet<Entry<K, V>> createEntrySet() { return new EntrySet(); } private class EntrySet extends ImmutableMapEntrySet<K, V> { @Override public UnmodifiableIterator<Entry<K, V>> iterator() { return asList().iterator(); } @Override ImmutableList<Entry<K, V>> createAsList() { return new ImmutableAsList<Entry<K, V>>() { // avoid additional indirection private final ImmutableList<K> keyList = keySet().asList(); @Override public Entry<K, V> get(int index) { return Maps.immutableEntry(keyList.get(index), valueList.get(index)); } @Override ImmutableCollection<Entry<K, V>> delegateCollection() { return EntrySet.this; } }; } @Override ImmutableMap<K, V> map() { return RegularImmutableSortedMap.this; } } @Override public ImmutableSortedSet<K> keySet() { return keySet; } @Override public ImmutableCollection<V> values() { return valueList; } @Override public V get(@Nullable Object key) { int index = keySet.indexOf(key); return (index == -1) ? null : valueList.get(index); } private ImmutableSortedMap<K, V> getSubMap(int fromIndex, int toIndex) { if (fromIndex == 0 && toIndex == size()) { return this; } else if (fromIndex == toIndex) { return emptyMap(comparator()); } else { return from( keySet.getSubSet(fromIndex, toIndex), valueList.subList(fromIndex, toIndex)); } } @Override public ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) { return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive)); } @Override public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) { return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size()); } @Override ImmutableSortedMap<K, V> createDescendingMap() { return new RegularImmutableSortedMap<K, V>( (RegularImmutableSortedSet<K>) keySet.descendingSet(), valueList.reverse(), this); } }
Java
/* * Copyright (C) 2011 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 com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.Iterator; /** * An {@code Iterable} whose elements are sorted relative to a {@code Comparator}, typically * provided at creation time. * * @author Louis Wasserman */ @GwtCompatible interface SortedIterable<T> extends Iterable<T> { /** * Returns the {@code Comparator} by which the elements of this iterable are ordered, or {@code * Ordering.natural()} if the elements are ordered by their natural ordering. */ Comparator<? super T> comparator(); /** * Returns an iterator over elements of type {@code T}. The elements are returned in * nondecreasing order according to the associated {@link #comparator}. */ @Override Iterator<T> iterator(); }
Java