Class Streams


  • public class Streams
    extends Object
    • Constructor Detail

      • Streams

        public Streams()
    • Method Detail

      • iterateOnce

        public static <T> Iterable<T> iterateOnce​(Stream<T> stream)
        Iterates through stream only once. It's strongly recommended to avoid assigning the return value to a variable or passing it to any other method because the returned Iterable's iterator() method can only be called once. Instead, always use it together with a for-each loop, as in:
        
           for (Foo foo : iterateOnce(stream)) {
             ...
             if (...) continue;
             if (...) break;
             ...
           }
         
        The above is equivalent to manually doing:
        
           Iterable<Foo> foos = stream::iterator;
           for (Foo foo : foos) {
             ...
           }
         
        except using this API eliminates the need for a named variable that escapes the scope of the for-each loop. And code is more readable too.

        Note that iterateThrough() should be preferred whenever possible due to the caveats mentioned above. This method is still useful when the loop body needs to use control flows such as break or return.

      • iterateThrough

        public static <T,​E extends Throwable> void iterateThrough​(Stream<? extends T> stream,
                                                                        CheckedConsumer<? super T,​E> consumer)
                                                                 throws E extends Throwable
        Iterates through stream sequentially and passes each element to consumer with exceptions propagated. For example:
        
           void writeAll(Stream<?> stream, ObjectOutput out) throws IOException {
             iterateThrough(stream, out::writeObject);
           }
         
        Throws:
        E extends Throwable