Iterate an Enumeration in Java 8
Since Java-9 there will be new default method Enumeration.asIterator()
which will make pure Java solution simpler:
nets.asIterator().forEachRemaining(iface -> { ... });
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)…
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(...));
(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);