How do I sort strings data using CollationKey class?

When the strings must be compared multiple times, for example when sorting a list of strings. It’s more efficient to use CollationKey class. Using CollationKey to compare strings is generally faster than using Collator.compare().

You can not create CollationKey directly. Rather, generate them by calling Collator.getCollationKey() method. You can only compare CollationKey generated from the same Collator object.

package org.kodejava.text;

import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;

public class CollationKeyExample {
    public static void main(String[] args) {
        String[] countries = {
                "German",
                "United Kingdom",
                "United States",
                "French",
                "Japan",
                "Myanmar",
                "India"
        };

        System.out.println("original:");
        System.out.println(Arrays.toString(countries));

        // Gets Collator object of default locale
        Collator collator = Collator.getInstance();

        // Creates and initializes CollationKey array
        CollationKey[] keys = new CollationKey[countries.length];

        for (int i = 0; i < countries.length; i++) {
            // Generate CollationKey by calling
            // Collator.getCollationKey() method then assign into
            // keys which is an array of CollationKey.
            // The CollationKey for the given String based on the 
            // Collator's collation rules.
            keys[i] = collator.getCollationKey(countries[i]);
        }

        // Sort the keys array
        Arrays.sort(keys);

        // Print out the sorted array
        System.out.println("sorted result: ");
        StringBuilder sb = new StringBuilder();
        for (CollationKey key : keys) {
            sb.append(key.getSourceString()).append(",");
        }
        System.out.println(sb);
    }
}

Below is the result of the program:

original:
[German, United Kingdom, United States, French, Japan, Myanmar, India]
sorted result: 
French,German,India,Japan,Myanmar,United Kingdom,United States,

How do I sort string of numbers in ascending order?

In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8" in ascending order, so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10".

package org.kodejava.util;

import java.util.Arrays;

public class SortStringNumber {
    public static void main(String[] args) {
        // We have some string numbers separated by comma. First we
        // need to split it, so we can get each individual number.
        String data = "2, 5, 9, 1, 10, 7, 4, 8";
        String[] numbers = data.split(",");

        // Convert the string numbers into Integer and placed it into
        // an array of Integer.
        Integer[] intValues = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intValues[i] = Integer.parseInt(numbers[i].trim());
        }

        // Sort the number in ascending order using the
        // Arrays.sort() method.
        Arrays.sort(intValues);

        // Convert back the sorted number into string using the
        // StringBuilder object. Prints the sorted string numbers.
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < intValues.length; i++) {
            Integer intValue = intValues[i];
            builder.append(intValue);
            if (i < intValues.length - 1) {
                builder.append(", ");
            }
        }
        System.out.println("Before = " + data);
        System.out.println("After  = " + builder);
    }
}

When we run the program we will get the following output:

Before = 2, 5, 9, 1, 10, 7, 4, 8
After  = 1, 2, 4, 5, 7, 8, 9, 10

How do I sort a 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

How do I sort LinkedList elements?

To sort the elements of LinkedList we can use the Collections.sort(List<T> list) static methods. The default order of the sorting is a descending order.

package org.kodejava.util;

import java.util.LinkedList;
import java.util.Collections;

public class LinkedListSort {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("E");
        grades.add("C");
        grades.add("A");
        grades.add("F");
        grades.add("B");
        grades.add("D");

        System.out.println("Before sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        // Sort the elements of linked list based on its data
        // natural order.
        Collections.sort(grades);

        System.out.println("After sorting:");
        System.out.println("===============");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are:

Before sorting:
===============
Grade = E
Grade = C
Grade = A
Grade = F
Grade = B
Grade = D
After sorting:
===============
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F

How do I search collection elements?

This code example use the Collections.binarySearch() to search an specified object inside a specified collections. Prior to calling the binarySearch() method we need to sort the elements of the collection. If the object is not sorted according to their natural order the search result will be undefined.

package org.kodejava.util;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Collections;
import java.text.DateFormatSymbols;

public class CollectionSearch {
    public static void main(String[] args) {
        DateFormatSymbols dfs = new DateFormatSymbols();

        LinkedList<String> monthList =
                new LinkedList<>(Arrays.asList(dfs.getMonths()));

        // Sort the collection elements
        Collections.sort(monthList);
        System.out.println("Months = " + monthList);

        // Get the position of November inside the monthList. It returns a positive
        // value if the item found in the monthList.
        int index = Collections.binarySearch(monthList, "November");
        if (index > 0) {
            System.out.println("Found at index = " + index);
            System.out.println("Month = " + monthList.get(index));
        }
    }
}

The output of the code snippet above is below.

Months = [, April, August, December, February, January, July, June, March, May, November, October, September]
Found at index = 10
Month = November