How do I sort an Enumeration?

package org.kodejava.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<>();
        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 = 574156412
Number = 692265226
Number = 852855412
Number = 858413518
Number = 1272648602
Number = 1851829368
Number = 1960139525
Number = 2053222887
Number = 2055598873
Number = 2081007654

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA.

1 Comments

Leave a Reply