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.
(This answer shows one of many options. Just because is
hashad acceptance mark, doesn't mean it is the best one. I suggest reading other answers and picking one depending on situation you are in. Personally for Java 8 I find Holger's answer nicest because it is also simple but doesn't need additional iteration - which happens in mine solution. But for Java 9 solution visit Tagir Valeev answer)You can copy elements from your
Enumeration
toArrayList
withCollections.list
and then use it likeIn 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:Then you can simply do
forEachRemaining(enumeration, lambda-expression);
(mind theimport static
feature)…You can use the following combination of standard functions:
You may also add more characteristics like
NONNULL
orDISTINCT
.After applying static imports this will become more readable:
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 useIteratorUtils.asIterator()
from Apache Commons Collections 3.2Iterators.forEnumeration()
from Google GuavaSince Java-9 there will be new default method
Enumeration.asIterator()
which will make pure Java solution simpler:For Java 8 the simplest transformation of enumeration to stream is:
Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
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: