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

Paul Sandoz paul.sandoz at oracle.com
Tue Jun 14 23:04:55 UTC 2016


> On 14 Jun 2016, at 13:11, Patrick Reinhart <patrick at reini.net> wrote:
> 
> Hi Paul,
> 
> I see the point, that making it too easy there.  I might have to some
> little explain where I have started from. I wanted to go over all
> resource URL's from a ClassLoader and read them as a Stream:
> 
> Enumeration<URL> resources =
> myInstance.getClassLoader().getResources("resource.name");
> Collections.list(resources).stream()....
> 
> Which will internally copy all elements right away into an ArrayList and
> does more than I wanted... :-)
> 

Right. A Spliterator from an Iterator will only copy elements (a prefix of increasing size) when splitting.


> So, with that your good reasons in mind, in my case leaded me in a wrong
> solution in the first attempt too - thanks good I looked into the source
> code ;-)
> 
> In my case then is the used approach to get a Stream correct?
> 

Almost:

- you can use Enumeration.asIterator() rather than creating your own.

- I don’t think you can assume the Iterator has an encounter order (even though there is a form of order related to class loader hierarchy, i.e. you cannot assume resources from a particular class loader are presented in any particular order, it might depend on how the zip/jar was created or the order in which resources are presented in the JDK image, which IIRC the order might optimized for booting up).

I had marked ClassLoader as an area to use Stream (we went through a bunch of areas that return Enumeration and add Stream-based methods e.g. NetworkInterface) but we held off because Jigsaw was doing a lot of plumbing work.

It might be possible to revisit, it’s the type of enhancement we could get a Feature Complete (FC) extension for. I cannot promise anything here, but if you are looking for something to contribute that may be a good area of focus on now Jigsaw is settling down.

Paul.


More information about the core-libs-dev mailing list