Java9 'asIterator' equivalent implementation in Java8

Below peace of code is using asIterator() method from Java9 can someone please help me to convert below code compatible with Java8?

private static Function<ClassLoader, Stream<URL>> asURLs(String packageDir) {
    return cl -> {
      try {
        Iterator<URL> iterator = cl.getResources(packageDir).asIterator();
            Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
      } catch (IOException e) {
        throw new UnhandledIOException(e);

>Solution :

To begin with, look up "jdk source code" in your favourite search engine to find the source of asIterator, so that you can copy it. You’ll find it here:

There you’ll find Enumeration.asIterator(), which is an interface default method. You can define it locally as a method that takes an Enumeration argument:

private static Iterator<E> asIterator(Enumeration<E> enumeration) {
    return new Iterator<>() {
        @Override public boolean hasNext() {
            return enumeration.hasMoreElements();
        @Override public E next() {
            return enumeration.nextElement();

and then use it like this:

    Iterator<URL> iterator = asIterator(cl.getResources(packageDir));

However, @tevemadar commented with a link to an answer to a related question that might suit you better

Leave a Reply