Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Enumeration to List


When using legacy libraries sometimes you need to convert Java Enumeration to List to use it with modern code it comfortable way. Again Java Collections API comes to the rescue!


The following Java example shows how to use legacy Enumeration in modern Java code. Also note how the content disappears from enumeration:


import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class CollectionsListEnumeration {

    public static void main(String[] args) {
        List<String> items = Arrays.asList("evaporating", "content");

        Enumeration<String> en = Collections.enumeration(items);

        // Legacy Enumeration to List:
        List<String> list = Collections.list(en);
        System.out.println("As list (content is gone!): " + list);

        // Again, but without iterating:
        en = Collections.enumeration(items);
        list = Collections.list(en);
        System.out.println("\nAs list: " + list);

    private static void print(Enumeration<String> en) {
        System.out.println("Enumeration: ");
        while (en.hasMoreElements()) {

Here, the key methods is java.util.Collections.list(Enumeration) that turns legacy Java Enumeration into List. The code is simple, but note that content of enumeration once used is gone!

The output of running the example illustrates that:

As list (content is gone!): []

As list: [evaporating, content]

Printing the content of Enumeration makes it empty. Also creating a List from Enumeration makes the content disappear, which means that Enumeration cannot be reused.

Share with the World!