In this example we demonstrate how to use the java.text.Collator
class to sort strings in language-specific order. Using the java.text.Collator
class makes the string not just sorted by the ASCII code of their characters, but it will follow the language natural order of the characters.
package org.kodejava.text;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.text.Collator;
public class StringShortWithCollator {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Guava");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
fruits.add("Apple");
// Define a collator for US English.
Collator collator = Collator.getInstance(Locale.US);
// Sort the list base on the collator
fruits.sort(collator);
for (String fruit : fruits) {
System.out.println("Fruit = " + fruit);
}
}
}
The result of the code snippet above are:
Fruit = Apple
Fruit = Banana
Fruit = Guava
Fruit = Mango
Fruit = Orange
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024