Enumeration Bridge To Stream And Iterator

Vector.elements() returns an Enumeration; asIterator and Collections.list bridge it into for-each and the Stream API without rewriting legacy code.

JavaCli Tooling

Code

snippet
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;

public class EnumerationBridge {

    public static void main(String[] args) {
        Vector<String> legacy = new Vector<>();
        legacy.add("alpha");
        legacy.add("beta");

        // legacy APIs hand out Enumeration: pull with hasMoreElements/nextElement
        Enumeration<String> elements = legacy.elements();
        while (elements.hasMoreElements()) {
            System.out.println("enumeration: " + elements.nextElement());
        }

        // asIterator (Java 9+) bridges the same handle into enhanced for
        Iterable<String> iterable = () -> legacy.elements().asIterator();
        for (String value : iterable) {
            System.out.println("for-each: " + value);
        }

        // for the Stream API, materialize into a List first
        List<String> list = Collections.list(legacy.elements());
        String joined = list.stream()
                .map(String::toUpperCase)
                .collect(Collectors.joining(","));
        System.out.println("stream: " + joined);
    }
}

Inside this example — Enumeration Bridge To Stream And Iterator

All of the logic lives in the class EnumerationBridge and the function main.

The loop while (elements.hasMoreElements()) is the only repeated construct. The pipeline is a stream: source, lazy intermediate steps, one terminal collector.

What to watch for

  • Dependencies: none by design — no registry lookups, no lockfile lines.

Using it

The entry-point signature is public static void main(String[] args)

The demo output is labeled (enumeration:, for-each:, stream:); each label names the call that printed it.

Key statements

.collect(Collectors.joining(","));

Interactive Tools for This Topic

FAQ

What does Enumeration Bridge To Stream And Iterator print when run?
Running the file directly is enough — expect labeled output lines such as `enumeration:`, `for-each:`, `stream:`.