0

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);
      }
    };
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92
  • 2
    You could "steal" it from a newer JDK, it's a couple lines of code: https://github.com/openjdk/jdk/blob/ad348a8cec50561d3e295b6289772530f541c6b1/src/java.base/share/classes/java/util/Enumeration.java#L119 - I think that may have happened in this answer once: https://stackoverflow.com/a/23276455/7916438 – tevemadar May 15 '23 at 11:18

1 Answers1

1

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

k314159
  • 5,051
  • 10
  • 32