Java: Enumeration from Set<String>

Java: Enumeration from Set<String>

To create an Enumeration from a Set<String> in Java, you can use the Collections.enumeration() method, which converts the elements of the Set into an Enumeration. Here's an example:

import java.util.*; public class SetToEnumerationExample { public static void main(String[] args) { Set<String> stringSet = new HashSet<>(); stringSet.add("One"); stringSet.add("Two"); stringSet.add("Three"); Enumeration<String> enumeration = Collections.enumeration(stringSet); while (enumeration.hasMoreElements()) { String element = enumeration.nextElement(); System.out.println(element); } } } 

In this example:

  1. We create a Set<String> named stringSet and add some string elements to it.

  2. We use Collections.enumeration(stringSet) to convert the Set into an Enumeration<String>.

  3. We iterate over the elements of the Enumeration using a while loop and enumeration.hasMoreElements(), and we retrieve each element with enumeration.nextElement().

The Collections.enumeration() method is a convenient way to work with Enumeration when you have a Set or another collection that you want to iterate over using an Enumeration.


More Tags

broken-pipe java-12 springsource dylib background androidx yuv ubuntu-18.04 ssh-keygen one-time-password

More Java Questions

More Tax and Salary Calculators

More Pregnancy Calculators

More Internet Calculators

More Statistics Calculators