An array can be sorted in case-insensitive order using the java. util. Arrays. sort() method.
Case-insensitive Sorting By default, the sort() method sorts the list in ASCIIbetical order rather than actual alphabetical order. This means uppercase letters come before lowercase letters.
localeCompare() enables case-insensitive sorting for an array.
Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);
It is very unclear what you are trying to do, but you can sort a list like this:
List<String> fruits = new ArrayList<String>(7);
fruits.add("Pineapple");
fruits.add("apple");
fruits.add("apricot");
fruits.add("Banana");
fruits.add("mango");
fruits.add("melon");
fruits.add("peach");
System.out.println("Unsorted: " + fruits);
Collections.sort(fruits, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
System.out.println("Sorted: " + fruits);
Collections.sort()
lets you pass a custom comparator for ordering. For case insensitive ordering String
class provides a static final comparator called CASE_INSENSITIVE_ORDER
.
So in your case all that's needed is:
Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);
Here's a plain java example of the best way to do it:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sorter {
String fruits[] = new String[7];
List<String> lst;
Sorter() {
lst = new ArrayList<String>();
// initialise UNSORTED array
fruits[0] = "Melon"; fruits[1] = "apricot"; fruits[2] = "peach";
fruits[3] = "mango"; fruits[4] = "Apple"; fruits[5] = "pineapple";
fruits[6] = "banana";
}
public static void main(String[] args) {
Sorter srt = new Sorter();
srt.anyOldUnstaticMethod();
}
public void anyOldUnstaticMethod() {
Collections.addAll(lst, fruits);
System.out.println("Initial List");
for (String s : lst)
System.out.println(s);
Collections.sort(lst);
System.out.println("\nSorted List");
for (String s : lst)
System.out.println(s);
Collections.sort(lst, new SortIgnoreCase());
System.out.println("\nSorted Ignoring Case List");
for (String s : lst)
System.out.println(s);
}
public class SortIgnoreCase implements Comparator<Object> {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
}
I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.
You should almost always use a Collator for dictionary based sorting.
For case insensitive collator searching for the English language you do the following:
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With