clcron / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
1 stars 0 forks source link

Feature: Iterables.once() #585

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Sometimes, it's useful to provide an Iterable object that traverses a known 
Iterator only once, without writing the boilerplate wrapper for it. This makes 
it easier to write loops or return Iterable instances from methods in some 
cases.

I have created the following static utility method, contributed as public 
domain. The formatting might not match project standards, so reformat as you 
see fit.

    /**
     * Provides an {@link Iterable} object that can be iterated only once, by
     * returning the provided iterator. Subsequent calls to
     * {@link Iterable#iterator()} will return an empty iterator.
     * 
     * @param <T>
     *            type of elements
     * @param iterator
     *            first iterator to return
     * @return iterable wrapper
     */
    public static <T> Iterable<T> once(final Iterator<T> iterator) {
        return new Iterable<T>() {
            private Iterator<T> iter = iterator;

            @Override
            public Iterator<T> iterator() {
                if (iter == null)
                    return Iterators.emptyIterator();

                Iterator<T> val = iter;
                iter = null;
                return val;
            }
        };
    }

Original issue reported on code.google.com by tv@duh.org on 30 Mar 2011 at 1:53

GoogleCodeExporter commented 9 years ago
This is in the IdeaGraveyard as something Guava is opposed to providing. Even 
if the intent is to just adapt an Iterator for a single use in a for-each loop, 
the method still returns an Iterable that breaks the expectation that it can be 
used to produce multiple viable Iterators. That could lead to accidents if it's 
used in any other way than just directly in a for-each. It also doesn't save 
much in terms of code you have to write.

Original comment by cgdec...@gmail.com on 30 Mar 2011 at 4:21

GoogleCodeExporter commented 9 years ago
This is too bad. While I understand the philosophy behind rejecting this, it is 
also a feature I often miss, and I think it doesn't violate the contract any 
more than e.g. Iterables.consumingIterable() does.

Original comment by SeanPFl...@googlemail.com on 4 Apr 2011 at 7:58

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:15

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:09