All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.common.collect.Collections2 Maven / Gradle / Ivy

Go to download

Google Collections Library is a suite of new collections and collection-related goodness for Java 5.0

There is a newer version: 1.0
Show newest version
/*
 * Copyright (C) 2008 Google Inc.
 *
 * 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.base.Function;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.Nullable;
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.Set;

/**
 * Provides static methods for working with {@code Collection} instances.
 *
 * @author Chris Povirk
 * @author Mike Bostock
 * @author Jared Levy
 */
public final class Collections2 {
  private Collections2() {}

  /**
   * Returns {@code true} if the collection {@code self} contains all of the
   * elements in the collection {@code c}.
   *
   * 

This method iterates over the specified collection {@code c}, checking * each element returned by the iterator in turn to see if it is contained in * the specified collection {@code self}. If all elements are so contained, * {@code true} is returned, otherwise {@code false}. * * @param self a collection which might contain all elements in {@code c} * @param c a collection whose elements might be contained by {@code self} */ // TODO: Make public? static boolean containsAll(Collection self, Collection c) { checkNotNull(self); for (Object o : c) { if (!self.contains(o)) { return false; } } return true; } /** * 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 same iteration order. */ static Collection toCollection(Iterable iterable) { return (iterable instanceof Collection) ? (Collection) iterable : Lists.newArrayList(iterable); } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The * returned collection is a live view of {@code unfiltered}; changes to one * affect the other. * *

The resulting collection's iterator does not support {@code remove()}, * but all other collection methods are supported. The collection's * {@code add()} and {@code addAll()} methods throw an * {@link IllegalArgumentException} if an element that doesn't satisfy the * predicate is provided. When methods such as {@code removeAll()} and * {@code clear()} are called on the filtered collection, only elements that * satisfy the filter will be removed from the underlying collection. * *

The returned collection isn't threadsafe or serializable, even if * {@code unfiltered} is. * *

Many of the filtered collection's methods, such as {@code size()}, * iterate across every element in the underlying collection and determine * which elements satisfy the filter. When a live view is not needed, * it may be faster to copy the filtered collection and use the copy. */ public static Collection filter( Collection unfiltered, Predicate predicate) { if (unfiltered instanceof FilteredCollection) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredCollection filtered = (FilteredCollection) unfiltered; Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); return new FilteredCollection(filtered.unfiltered, combinedPredicate); } return new FilteredCollection( checkNotNull(unfiltered), checkNotNull(predicate)); } static class FilteredCollection implements Collection { final Collection unfiltered; final Predicate predicate; FilteredCollection(Collection unfiltered, Predicate predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } public boolean add(E element) { checkArgument(predicate.apply(element)); return unfiltered.add(element); } public boolean addAll(Collection collection) { for (E element : collection) { checkArgument(predicate.apply(element)); } return unfiltered.addAll(collection); } public void clear() { Iterator iterator = unfiltered.iterator(); while (iterator.hasNext()) { E element = iterator.next(); if (predicate.apply(element)) { iterator.remove(); } } } // if a ClassCastException occurs, contains() returns false @SuppressWarnings("unchecked") public boolean contains(Object element) { try { return predicate.apply((E) element) && unfiltered.contains(element); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } public boolean containsAll(Collection collection) { for (Object element : collection) { if (!contains(element)) { return false; } } return true; } public boolean isEmpty() { return !Iterators.any(unfiltered.iterator(), predicate); } public Iterator iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } // if a ClassCastException occurs, remove() returns false @SuppressWarnings("unchecked") public boolean remove(Object element) { try { return predicate.apply((E) element) && unfiltered.remove(element); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } public boolean removeAll(Collection collection) { checkNotNull(collection); boolean changed = false; Iterator iterator = unfiltered.iterator(); while (iterator.hasNext()) { E element = iterator.next(); if (predicate.apply(element) && collection.contains(element)) { iterator.remove(); changed = true; } } return changed; } public boolean retainAll(Collection collection) { checkNotNull(collection); boolean changed = false; Iterator iterator = unfiltered.iterator(); while (iterator.hasNext()) { E element = iterator.next(); if (predicate.apply(element) && !collection.contains(element)) { iterator.remove(); changed = true; } } return changed; } public int size() { return Iterators.size(iterator()); } public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } public T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } @Override public String toString() { return Iterators.toString(iterator()); } } /** * Returns a collection that applies {@code function} to each element of * {@code fromCollection}. The returned collection is a live view of {@code * fromCollection}; changes to one affect the other. * *

The returned collection's {@code add()} and {@code addAll()} methods * throw an {@link UnsupportedOperationException}. All other collection * methods are supported, as long as {@code fromCollection} supports them. * *

The returned collection isn't threadsafe or serializable, even if * {@code fromCollection} is. * *

When a live view is not needed, it may be faster to copy the * transformed collection and use the copy. */ static Collection transform(Collection fromCollection, Function function) { return new TransformedCollection(fromCollection, function); } static class TransformedCollection extends AbstractCollection { final Collection fromCollection; final Function function; TransformedCollection(Collection fromCollection, Function function) { this.fromCollection = checkNotNull(fromCollection); this.function = checkNotNull(function); } @Override public void clear() { fromCollection.clear(); } @Override public boolean isEmpty() { return fromCollection.isEmpty(); } @Override public Iterator iterator() { return Iterators.transform(fromCollection.iterator(), function); } @Override public boolean removeAll(Collection c) { return super.removeAll(checkNotNull(c)); } @Override public boolean retainAll(Collection c) { return super.retainAll(checkNotNull(c)); } @Override public int size() { return fromCollection.size(); } } static boolean setEquals(Set thisSet, @Nullable Object object) { if (object == thisSet) { return true; } if (object instanceof Set) { Set thatSet = (Set) object; return thisSet.size() == thatSet.size() && thisSet.containsAll(thatSet); } return false; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy