Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate an Enumeration in Java 8

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.

like image 639
Tapas Bose Avatar asked Apr 24 '14 06:04

Tapas Bose


People also ask

Can we iterate enum in Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.

Can we iterate over enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.


3 Answers

(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);
like image 173
Pshemo Avatar answered Nov 15 '22 15:11

Pshemo


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(...));
like image 35
nosid Avatar answered Nov 15 '22 15:11

nosid


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

nets.asIterator().forEachRemaining(iface -> { ... });
like image 25
Tagir Valeev Avatar answered Nov 15 '22 13:11

Tagir Valeev