Collections

Get Enumeration from Collection example

In this example we shall show you how to get an Enumeration from a Collection. We are using an ArrayList, but the same API applies to any type of Collection implementation class e.g. HashSet, TreeSet, LinkedHashSet, LinkedList, Vector etc. To get an Enumeration from an ArrayList one should perform the following steps:

  • Create an ArrayList.
  • Populate the arrayList with elements, with add(E e) API method of ArrayList.
  • Invoke the enumeration(Collection c) API method of Collections, to get the enumeration object over the specified Collection, which is an ArrayList in the example.
  • Get the elements of the enumeration, with hasMoreElements(), nextElement() API method of Enumeration,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;
 
import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;
 
public class EnumerationOverCollection {
 
  public static void main(String[] args) {

    /*

Please note that the same API applies to any type of 

Collection implementation class e.g. 

HashSet, TreeSet, LinkedHashSet, LinkedList, Vector etc
     */

    // Create an ArrayList and populate it with elements
    ArrayList arrayList = new ArrayList();
    arrayList.add("element_1");
    arrayList.add("element_2");
    arrayList.add("element_3");
    arrayList.add("element_4");
    arrayList.add("element_5");
 
    // static Enumeration enumeration(Collection c) method returns the enumeration object over the specified Collection
    Enumeration enumeration = Collections.enumeration(arrayList);
 
    System.out.println("Enumerating through ArrayList");
    while(enumeration.hasMoreElements())

System.out.println(enumeration.nextElement());
  }
}

Output:

Enumerating through ArrayList
element_1
element_2
element_3
element_4
element_5

 
This was an example of how to get an Enumeration from a Collection in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button