Collection to Enumeration conversion

In this post under Java Collections, I will show with example how to convert a collection to Enumeration.

Below is the complete code for your reference.

Main class

1  package core.collection;
2  
3  import java.util.Collections;
4  import java.util.Enumeration;
5  import java.util.List;
6  import java.util.ArrayList;
7  
8  public class ColToEnumDemo {
9      public static void main(String args[]) {
10         List<Integer> integerList = new ArrayList<>(0);
11         integerList.add(1);
12         integerList.add(2);
13         integerList.add(3);
14         integerList.add(4);
15         integerList.add(5);
16 
17         Enumeration<Integer> enumeration = Collections.enumeration(integerList);
18 
19         while(enumeration.hasMoreElements()) {
20             System.out.print(enumeration.nextElement() + ",");
21         }
22     }
23 }

In the above code, at line 10, I create an list of type argument “Integer” class.

Then I populate the list with 5 elements.

Then at line 17, I call the static method “enumeration” available on “Collections” class and pass the integer list as an argument.

This “enumeration” method takes a Collection as an argument.

The return value of the static method is an instance of “Enumeration” class of type argument “Integer”.

In this way we can convert a Collection to Enumeration.

Leave a comment