80

Is it possible to iterate an Enumeration by using Lambda Expression? What will be the Lambda representation of the following code snippet:

Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

while (nets.hasMoreElements()) {
    NetworkInterface networkInterface = nets.nextElement();

}

I didn't find any stream within it.

5
  • 7
    Enumerations were replaced by Iterators in Java 1.2 in 1998. It is unfortunate you still have to use it. :| Apr 24, 2014 at 6:56
  • 1
    You can adapt your Enumeration to Iterator: stackoverflow.com/questions/5007082/…
    – marcinj
    Apr 24, 2014 at 6:59
  • 8
    @PeterLawrey Iterator came along, but there are still core APIs which use Enumeration. Generics came along, but there are still core APIs which use bare types or return Object. Lambdas came along, but Swing is still full of multi-method interfaces, so we can't use them. It doesn't really surprise me anymore when I find APIs which Java forgot to modernise; it just saddens me.
    – Hakanai
    Aug 18, 2014 at 7:01
  • 3
    @Trejkaz Yes, Swing still uses Vector and Hashtable. Aug 18, 2014 at 13:49
  • 1
    @PeterLawrey the Servlet API still uses Enumerations.
    – OrangeDog
    Oct 30, 2018 at 13:57

7 Answers 7

98

(This answer shows one of many options. Just because is has had acceptance mark, doesn't mean it is the best one. I suggest reading other answers and picking one depending on situation you are in. IMO:

  • for Java 8 Holger's answer is nicest, because aside from being simple it doesn't require additional iteration which happens in my solution.
  • for Java 9 I would pick solution describe in Tagir Valeev answer)

You can copy elements from your Enumeration to ArrayList with Collections.list and then use it like

Collections.list(yourEnumeration).forEach(yourAction);
3
  • 18
    The catch is that now you have to store all the elements in a list. Which if it's small, is probably fine. But it's worth mentioning, because sometimes it will be too big to fit in memory.
    – Hakanai
    Aug 18, 2014 at 7:02
  • How about java.util.stream.Stream#of(yourEnumeration.values()).forEach()?
    – Filip
    Dec 6, 2016 at 12:16
  • 4
    @Filip Your comment is about Enum but question is about Enumeration.
    – Pshemo
    Dec 6, 2016 at 13:18
52

If there are a lot of Enumerations in your code, I recommend creating a static helper method, that converts an Enumeration into a Stream. The static method might look as follows:

public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            new Iterator<T>() {
                public T next() {
                    return e.nextElement();
                }
                public boolean hasNext() {
                    return e.hasMoreElements();
                }
            },
            Spliterator.ORDERED), false);
}

Use the method with a static import. In contrast to Holger's solution, you can benefit from the different stream operations, which might make the existing code even simpler. Here is an example:

Map<...> map = enumerationAsStream(enumeration)
    .filter(Objects::nonNull)
    .collect(groupingBy(...));
4
  • I think both are complementing each other just like list.forEach(…) and list.stream(). ⟨stream ops⟩ .forEach(…).
    – Holger
    Apr 24, 2014 at 18:20
  • 2
    How is this not part of the JDK?
    – Nick
    Aug 23, 2017 at 22:42
  • public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) { return Collections.list(e).stream(); } would do the same, but much simpler. Jan 29, 2018 at 15:01
  • 2
    @ThomasFritsch's proposal makes an intermediate copy of the list, which is what's being avoided. Jan 6, 2019 at 1:46
52

Since Java-9 there will be new default method Enumeration.asIterator() which will make pure Java solution simpler:

nets.asIterator().forEachRemaining(iface -> { ... });
0
42

In case you don’t like the fact that Collections.list(Enumeration) copies the entire contents into a (temporary) list before the iteration starts, you can help yourself out with a simple utility method:

public static <T> void forEachRemaining(Enumeration<T> e, Consumer<? super T> c) {
  while(e.hasMoreElements()) c.accept(e.nextElement());
}

Then you can simply do forEachRemaining(enumeration, lambda-expression); (mind the import static feature)…

0
12

You can use the following combination of standard functions:

StreamSupport.stream(Spliterators.spliteratorUnknownSize(CollectionUtils.toIterator(enumeration), Spliterator.IMMUTABLE), parallel)

You may also add more characteristics like NONNULL or DISTINCT.

After applying static imports this will become more readable:

stream(spliteratorUnknownSize(toIterator(enumeration), IMMUTABLE), false)

now you have a standard Java 8 Stream to be used in any way! You may pass true for parallel processing.

To convert from Enumeration to Iterator use any of:

  • CollectionUtils.toIterator() from Spring 3.2 or you can use
  • IteratorUtils.asIterator() from Apache Commons Collections 3.2
  • Iterators.forEnumeration() from Google Guava
4
  • 1
    Where does CollectionUtils come from? Doesn’t seem to be in the JDK.
    – Martin
    Jun 2, 2015 at 18:42
  • @Martin, it seems to be org.apache.commons.collections.CollectionUtils.
    – Vadzim
    Jul 5, 2015 at 16:54
  • @Vadzim I checked Apache Commons Collections 1.0, 2.0, 2.1.1, 3.2.1 and 4.0, but no class named CollectionUtils contains a method named toIterator.
    – Martin
    Jul 6, 2015 at 17:09
  • Sorry, was confused, got it from Spring 3.2 Jul 7, 2015 at 13:49
8

For Java 8 the simplest transformation of enumeration to stream is:

Collections.list(NetworkInterface.getNetworkInterfaces()).stream()

5

I know this is an old question but I wanted to present an alternative to Collections.asList and Stream functionality. Since the question is titled "Iterate an Enumeration", I recognize sometimes you want to use a lambda expression but an enhanced for loop may be preferable as the enumerated object may throw an exception and the for loop is easier to encapsulate in a larger try-catch code segment (lambdas require declared exceptions to be caught within the lambda). To that end, here is using a lambda to create an Iterable which is usable in a for loop and does not preload the enumeration:

 /**
 * Creates lazy Iterable for Enumeration
 *
 * @param <T> Class being iterated
 * @param e Enumeration as base for Iterator
 * @return Iterable wrapping Enumeration
 */
public static <T> Iterable<T> enumerationIterable(Enumeration<T> e)
{
    return () -> new Iterator<T>()
    {
        @Override
        public T next()
        {
            return e.nextElement();
        }

        @Override
        public boolean hasNext()
        {
            return e.hasMoreElements();
        }
    };
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.