Iterate an Enumeration in Java 8

Tapas Bose picture Tapas Bose · Apr 24, 2014 · Viewed 51.7k times · Source

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.

Answer

Pshemo picture Pshemo · Apr 24, 2014

(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 mine solution.
- for Java 9 I would pick solution from 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);