Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java collections sort method for string is not working properly for case sensitive and special characters

Tags:

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?

like image 382
Prabal Srivastava Avatar asked Mar 18 '19 07:03

Prabal Srivastava


People also ask

How does Collections sort work in Java?

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.

How do you sort lowercase and uppercase in Java?

sort(caps); It is sorting like: Alpha Beta Delta alpha1 theta. Here it can take any type of string even uppercase / lowercase.


2 Answers

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] 
like image 82
Jaspreet Jolly Avatar answered Oct 04 '22 01:10

Jaspreet Jolly


You could create a custom comparator for your sorting logics. After this you can use it like this:

Collections.sort(yourArrayList, new YourComparator()); 
like image 23
ipave Avatar answered Oct 03 '22 23:10

ipave