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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.