Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
        return StreamSupport.stream(
            Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
      } catch (IOException e) {
        throw new UnhandledIOException(e);
      }
    };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading