Java9 'asIterator' equivalent implementation in Java8

121 Views Asked by At

Below piece of code is using asIterator() method from Java 9 can someone please help me to convert below code compatible with Java 8?

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

There are 1 best solutions below

3
k314159 On BEST ANSWER

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:

https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/Enumeration.java

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 <E> 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