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
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
Thank you very much. I solve my problem. Have a nice day~