Create java.util.stream.Stream from Iterator / Enumeration

Patrick Reinhart patrick at reini.net
Tue Jun 14 08:13:58 UTC 2016


Hi there,

I know you are busy getting the latest release ready. Still I have 
question according the java.util.stream.Stream's static helper methods. 
During my work I ran into a couple places where creating a Stream out of 
a Iterator or Enumeration directly would be quite handy.

At the moment I have made me two methods like this on a helper class in 
oder to not duplicate the code:

   public static <T> Stream<T> iterate(Iterator<T> iterator) {
     Objects.requireNonNull(iterator);
     return StreamSupport.stream(Spliterators
       .spliteratorUnknownSize(iterator, Spliterator.ORDERED | 
Spliterator.IMMUTABLE), false);
   }

   public static <T> Stream<T> iterate(Enumeration<T> enumeration) {
     Objects.requireNonNull(enumeration);
     final Iterator<T> iterator = new Iterator<T>() {
       @Override
       public boolean hasNext() {
         return enumeration.hasMoreElements();
       }

       @Override
       public T next() {
         return enumeration.nextElement();
       }
     };
     return iterate(iterator);
   }


My question is now, if it would be worth while having something like 
this on the Stream itself?


Cheers

Patrick


More information about the core-libs-dev mailing list