iterator() {
return Iterators.concat(iterators.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.
*
* Iterators returned by the returned iterable do not support the {@link
* Iterator#remove()} method.
*
*
Note: 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 Iterable> partition(
final Iterable iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new IterableWithToString>() {
public Iterator> 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.
*
* 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 Iterable> paddedPartition(
final Iterable iterable, final int size) {
checkNotNull(iterable);
checkArgument(size > 0);
return new IterableWithToString>() {
public Iterator> 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 Iterable filter(
final Iterable unfiltered, final Predicate super T> predicate) {
checkNotNull(unfiltered);
checkNotNull(predicate);
return new IterableWithToString() {
public Iterator 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
*/
public static Iterable filter(
final Iterable> unfiltered, final Class type) {
checkNotNull(unfiltered);
checkNotNull(type);
return new IterableWithToString() {
public Iterator iterator() {
return Iterators.filter(unfiltered.iterator(), type);
}
};
}
/**
* Returns {@code true} if one or more elements in {@code iterable} satisfy
* the predicate.
*/
public static boolean any(
Iterable 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 boolean all(
Iterable iterable, Predicate super T> predicate) {
return Iterators.all(iterable.iterator(), predicate);
}
/**
* Returns the first element in {@code iterable} that satisfies the given
* predicate.
*
* @throws NoSuchElementException if no element in {@code iterable} matches
* the given predicate
*/
public static T find(Iterable iterable,
Predicate super T> predicate) {
return Iterators.find(iterable.iterator(), predicate);
}
/**
* Returns an iterable that applies {@code function} to each element of {@code
* fromIterable}.
*
* 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.
*/
public static Iterable transform(final Iterable fromIterable,
final Function super F, ? extends T> function) {
checkNotNull(fromIterable);
checkNotNull(function);
return new IterableWithToString() {
public Iterator 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 get(Iterable iterable, int position) {
checkNotNull(iterable);
if (iterable instanceof List) {
return ((List) iterable).get(position);
}
if (iterable instanceof Collection) {
// Can check both ends
Collection collection = (Collection) iterable;
Preconditions.checkElementIndex(position, collection.size());
} else {
// Can only check the lower end
if (position < 0) {
throw new IndexOutOfBoundsException(
"position cannot be negative: " + position);
}
}
return Iterators.get(iterable.iterator(), position);
}
/**
* Returns the last element of {@code iterable}.
*
* @return the last element of {@code iterable}
* @throws NoSuchElementException if the iterable has no elements
*/
public static T getLast(Iterable iterable) {
if (iterable instanceof List) {
List list = (List) iterable;
// TODO: Support a concurrent list whose size changes while this method
// is running.
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return list.get(list.size() - 1);
}
if (iterable instanceof SortedSet) {
SortedSet sortedSet = (SortedSet) iterable;
return sortedSet.last();
}
return Iterators.getLast(iterable.iterator());
}
/**
* 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.
*
* 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.
*
*
The returned iterable's iterator supports {@code remove()} if the
* iterator of the underlying iterable supports it. Note that it is
* not 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}.
*/
public static Iterable skip(final Iterable iterable,
final int numberToSkip) {
checkNotNull(iterable);
checkArgument(numberToSkip >= 0, "number to skip cannot be negative");
if (iterable instanceof List) {
final List list = (List) iterable;
return new IterableWithToString() {
public Iterator iterator() {
// TODO: Support a concurrent list whose size changes while this
// method is running.
return (numberToSkip >= list.size())
? Iterators.emptyIterator()
: Platform.subList(list, numberToSkip, list.size()).iterator();
}
};
}
return new IterableWithToString() {
public Iterator iterator() {
final Iterator iterator = iterable.iterator();
Iterators.skip(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() {
boolean atStart = true;
public boolean hasNext() {
return iterator.hasNext();
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return iterator.next();
} finally {
atStart = false;
}
}
public void remove() {
if (atStart) {
throw new IllegalStateException();
}
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
*/
public static Iterable limit(
final Iterable iterable, final int limitSize) {
checkNotNull(iterable);
checkArgument(limitSize >= 0, "limit is negative");
return new IterableWithToString() {
public Iterator iterator() {
return Iterators.limit(iterable.iterator(), limitSize);
}
};
}
// Methods only in Iterables, not in Iterators
/**
* Adapts a list to an iterable with reversed iteration order. It is
* especially useful in foreach-style loops:
*
* List mylist = ...
* for (String str : Iterables.reverse(mylist)) {
* ...
* }
*
* @return an iterable with the same elements as the list, in reverse.
*/
public static Iterable reverse(final List list) {
checkNotNull(list);
return new IterableWithToString() {
public Iterator iterator() {
final ListIterator listIter = list.listIterator(list.size());
return new Iterator() {
public boolean hasNext() {
return listIter.hasPrevious();
}
public T next() {
return listIter.previous();
}
public void remove() {
listIter.remove();
}
};
}
};
}
/**
* Provides a rotated view of a list. Differs from {@link Collections#rotate}
* in that it leaves the underlying list unchanged. Note that this is a
* "live" view of the list that will change as the list changes. However, the
* behavior of an {@link Iterator} retrieved from a rotated view of the list
* is undefined if the list is structurally changed after the iterator is
* retrieved.
*
* @param list the list to return a rotated view of
* @param distance the distance to rotate the list. There are no constraints
* on this value; it may be zero, negative, or greater than {@code
* list.size()}.
* @return a rotated view of the given list
*/
public static Iterable rotate(final List list, final int distance) {
checkNotNull(list);
// If no rotation is requested, just return the original list
if (distance == 0) {
return list;
}
return new IterableWithToString() {
/**
* Determines the actual distance we need to rotate (distance provided
* might be larger than the size of the list or negative).
*/
int calcActualDistance(int size) {
// we already know distance and size are non-zero
int actualDistance = distance % size;
if (actualDistance < 0) {
// distance must have been negative
actualDistance += size;
}
return actualDistance;
}
public Iterator iterator() {
int size = list.size();
if (size <= 1) {
return list.iterator();
}
int actualDistance = calcActualDistance(size);
// lists of a size that go into the distance evenly don't need rotation
if (actualDistance == 0) {
return list.iterator();
}
@SuppressWarnings("unchecked")
Iterable rotated = concat(
Platform.subList(list, actualDistance, size),
Platform.subList(list, 0, actualDistance));
return rotated.iterator();
}
};
}
/**
* Returns whether the given iterable contains no elements.
*
* @return {@code true} if the iterable has no elements, {@code false} if the
* iterable has one or more elements
*/
public static boolean isEmpty(Iterable iterable) {
return !iterable.iterator().hasNext();
}
/**
* Removes the specified element from the specified iterable.
*
* This method iterates over the iterable, checking each element returned
* by the iterator in turn to see if it equals the object {@code o}. If they
* are equal, it is removed from the iterable with the iterator's
* {@code remove} method. At most one element is removed, even if the iterable
* contains multiple members that equal {@code o}.
*
*
Warning: Do not use this method for a collection, such as a
* {@link HashSet}, that has a fast {@code remove} method.
*
* @param iterable the iterable from which to remove
* @param o an element to remove from the collection
* @return {@code true} if the iterable changed as a result
* @throws UnsupportedOperationException if the iterator does not support the
* {@code remove} method and the iterable contains the object
*/
static boolean remove(Iterable> iterable, @Nullable Object o) {
Iterator> i = iterable.iterator();
while (i.hasNext()) {
if (Objects.equal(i.next(), o)) {
i.remove();
return true;
}
}
return false;
}
abstract static class IterableWithToString implements Iterable {
@Override public String toString() {
return Iterables.toString(this);
}
}
}