java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to sort an Enumeration?

package com.javacoderanch.example.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<Integer>();
        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 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 = 64029842
number = 72921309
number = 230054456
number = 256151404
number = 345486128
number = 387933255
number = 398974777
number = 626349261
number = 654063730
number = 1319397578