Array List of String Sort Method

i has a list of arrays with the following values

ArrayList [Admin,Readonly,CSR,adminuser,user,customer] 

when i used

 Collections.sort(ArrayList) 

I get the following result

 [Admin,CSR,Readonly,adminuser,customer,user] 

according to the Java doc, the above results are correct, but my expectation is (sorting whatever the case (upper / lower case)

 [Admin,adminuser,CSR,customer,Readonly,user] 

provide help on how to sort, regardless of the case in java, is there any other method available

Note: I will do an Automate test to check the sort order in the web table.

considers

Prabu

+7
java sorting arrays
source share
6 answers

It will happen,

 Collections.sort(yourList, String.CASE_INSENSITIVE_ORDER); 

I tried it

 ArrayList<String> myList=new ArrayList<String>(); Collections.addAll(myList,"Admin","Readonly","CSR","adminuser","user","customer"); System.out.println(myList); Collections.sort(myList, String.CASE_INSENSITIVE_ORDER); System.out.println(myList); 

the following result appeared

 [Admin, Readonly, CSR, adminuser, user, customer] [Admin, adminuser, CSR, customer, Readonly, user] 
+6
source share

You can use your own comparator in such a way as to sort regardless of the case (upper / lower case)

 Collections.sort(list, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); 
+4
source share

You can do with a custom comparator.

Try the following:

  // list containing String objects List<String> list = new ArrayList<>(); // call sort() with list and Comparator which // compares String objects ignoring case Collections.sort(list, new Comparator<String>(){ @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); 

You will need to pass an instance of Comparator to Collections.sort() , which compares String objects that are case-insensitive.

+2
source share
 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()); } } 

then

 Collections.sort(ArrayList, new SortIgnoreCase()); 
+1
source share
 Collections.sort(ArrayList, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.toLowerCase().compareTo(s2.toLowerCase()); } }); 
+1
source share

The answer is simple - capital letters have a lower number in ASCII . So the default comparison works fine.

0
source share

All Articles