How do I sort an java.util.Enumeration?

In this code snippet you will see how to sort the content of an Enumeration object. We start by creating a random numbers and stored it in a Vector. We use these numbers and create a Enumeration object by calling Vector‘s elements() method. We convert it to java.util.List and then sort the content of the List using Collections.sort() method. Here is the complete code snippet.

package org.kodejava.util;

import java.util.*;

public class EnumerationSort {
    public static void main(String[] args) {
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        Random random = new Random();
        Vector<Integer> data = new Vector<>();
        for (int i = 0; i < 10; i++) {
            data.add(Math.abs(random.nextInt()));
        }

        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally, we sort the list using
        // Collections.sort() method.
        Enumeration<Integer> enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        // Prints out all generated number after sorted.
        for (Integer number : list) {
            System.out.println("Number = " + number);
        }
    }
}

An example result of the code above is:

Number = 20742427
Number = 163885840
Number = 204704456
Number = 560032429
Number = 601762809
Number = 1300593322
Number = 1371678147
Number = 1786580321
Number = 1786731301
Number = 1856215303

1 Comments

Leave a Reply to James Kwon Cancel reply

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