Returns a view of iterable that skips its first numberToSkip elements. If iterable contains fewer than numberToSkip elements, the returned iterable skips all of its elements. Modifications to the underlying Iterable before a call to iterator() are
(final Iterable<T> iterable, final int numberToSkip)
| 822 | * @since 3.0 |
| 823 | */ |
| 824 | public static <T> Iterable<T> skip(final Iterable<T> iterable, final int numberToSkip) { |
| 825 | checkNotNull(iterable); |
| 826 | checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); |
| 827 | |
| 828 | if (iterable instanceof List) { |
| 829 | final List<T> list = (List<T>) iterable; |
| 830 | return new FluentIterable<T>() { |
| 831 | @Override |
| 832 | public Iterator<T> iterator() { |
| 833 | // TODO(kevinb): Support a concurrently modified collection? |
| 834 | int toSkip = Math.min(list.size(), numberToSkip); |
| 835 | return list.subList(toSkip, list.size()).iterator(); |
| 836 | } |
| 837 | }; |
| 838 | } |
| 839 | |
| 840 | return new FluentIterable<T>() { |
| 841 | @Override |
| 842 | public Iterator<T> iterator() { |
| 843 | final Iterator<T> iterator = iterable.iterator(); |
| 844 | |
| 845 | Iterators.advance(iterator, numberToSkip); |
| 846 | |
| 847 | /* |
| 848 | * We can't just return the iterator because an immediate call to its |
| 849 | * remove() method would remove one of the skipped elements instead of |
| 850 | * throwing an IllegalStateException. |
| 851 | */ |
| 852 | return new Iterator<T>() { |
| 853 | boolean atStart = true; |
| 854 | |
| 855 | @Override |
| 856 | public boolean hasNext() { |
| 857 | return iterator.hasNext(); |
| 858 | } |
| 859 | |
| 860 | @Override |
| 861 | public T next() { |
| 862 | T result = iterator.next(); |
| 863 | atStart = false; // not called if next() fails |
| 864 | return result; |
| 865 | } |
| 866 | |
| 867 | @Override |
| 868 | public void remove() { |
| 869 | checkRemove(!atStart); |
| 870 | iterator.remove(); |
| 871 | } |
| 872 | }; |
| 873 | } |
| 874 | }; |
| 875 | } |
| 876 | |
| 877 | /** |
| 878 | * Returns a view of {@code iterable} containing its first {@code limitSize} |
no test coverage detected