I was working on sorting a list of String in Java (1.8) and came to know that it is not working as expected!
I am trying the following code for sorting:
private Set<String> getTestData() { Set<String> compRoles = new HashSet<>(); compRoles.add("AA"); compRoles.add("Aa"); compRoles.add("aA"); compRoles.add("aa"); compRoles.add("11"); compRoles.add("117"); compRoles.add("12"); compRoles.add("21"); compRoles.add("!@"); compRoles.add("@!"); compRoles.add("@@!"); compRoles.add("BB"); compRoles.add("Bb"); compRoles.add("bb"); return compRoles; } public static void main(String args[]) { List<String> test = new ArrayList<>(new Test().getTestData()); System.out.println(test); Collections.sort(test); System.out.println(test); }
Before sort: [AA, Aa, aA, aa, 11, BB, Bb, bb, 12, @!, @@!, 117, 21, !@]
After sort: [!@, 11, 117, 12, 21, @!, @@!, AA, Aa, BB, Bb, aA, aa, bb]
My expectation is: [!@, @!, @@!, 11, 117, 12, 21, aa, aA, Aa, AA, bb, Bb, BB]
Do I need to use something else other that natural sort for this?
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order.
sort(caps); It is sorting like: Alpha Beta Delta alpha1 theta. Here it can take any type of string even uppercase / lowercase.
You can use the Collator class of Java.
public static void main(String[] args) { List<String> test = new ArrayList<>(new Test().getTestData()); System.out.println(test); test.sort(Collator.getInstance(Locale.ENGLISH)); System.out.println(test); }
Output:-
[AA, Aa, aA, aa, 11, BB, Bb, bb, 12, @!, @@!, 117, 21, !@] [!@, @!, @@!, 11, 117, 12, 21, aa, aA, Aa, AA, bb, Bb, BB]
You could create a custom comparator for your sorting logics. After this you can use it like this:
Collections.sort(yourArrayList, new YourComparator());
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