Java Programming Tutorials

Java programming tutorials with many code examples!

Java Enumeration to List

Problem:

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!

Solution:

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

package com.farenda.java;

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);
        print(en);

        // 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);
        print(en);
    }

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

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:

Enumeration:
evaporating
content
As list (content is gone!): []

As list: [evaporating, content]
Enumeration:

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!