Enumeration is an interface that was introduced in an older version of Java and is used to store a sequence of elements. An object that implements that interface generates a series of elements, one at a time. Calling the
nextElement method returns a successive element of the series. In the latest version of JDK, there are better ways to hold a sequence of elements that's why very often there is a need to convert older
Enumeration into something developers are more familiar with like for example
Enumeration interface is simple, it contains two methods:
hasMoreElements()- checks if this enumeration contains more elements,
nextElement()- returns the next element of this enumeration if this enumeration object has at least one more element to provide.
To print all elements from
Enumeration we could use
for statement like in the following example:
Spliterators using the newest
Iterator interface which is very similar to
Enumeration it seems like a good idea to use it for the conversion.
In the following example we created a helper method
enumerationAsStream that converts
Stream using that approach:
We created anonymous class that overrides three
In this approache, we don't have to know the exact number of elements hold in the
Stream using Guava
We could use external libraries such as
Guava to convert
Iterator and use it in
Spliterators. This is the same approach as in point 2 but here we could get rid of many lines of code:
In this example, we make use of Guava's
Iterators.forEnumeration(...) utility method.
Stream using Apache Common library
Another library we could use to convert
Iterator and then use it to create a
Stream out of it is
In this approache, we make use of Apache Commons
IteratorUtils.asIterator(...) helper method.
6. Java 9 solution
In Java 9 there is a possible way to convert an
Stream using a one-liner solution:
In Java 9 new method was introduced to the
default Iterator<E> asIterator()- this method returns an
Iteratorthat traverses the remaining elements covered by this enumeration.
There is also a way to convert
Stream by converting Iterator to Collection first, but in that approach, we will have to copy all elements, which could be very resource-consuming.
In this article, we presented how to convert an
Enumeration into a
As always, the source code used in this tutorial can be found on GitHub.