Array List of String Sorting Method

2020-03-18 06:09发布

i have an Array List with Following values

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

when i used

Collections.sort(ArrayList)

i'm getting the Following Result

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

as per the Java doc the above results are correct, but my Expectation is (sorting irrespective of case (upper / lower case)

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

provide an help how will do the sorting irrespective of case in java, is there any other method available

Note: i will do an Automate test for checking the sorting order in the Web table

regards

prabu

6条回答
冷血范
2楼-- · 2020-03-18 06:15
Collections.sort(ArrayList, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.toLowerCase().compareTo(s2.toLowerCase());
        }
    });
查看更多
时光不老,我们不散
3楼-- · 2020-03-18 06:21

You can do with custom Comparator.

Try this:

    // 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 Comparator instance in Collections.sort() method which compares String objects ignoring case.

查看更多
祖国的老花朵
4楼-- · 2020-03-18 06:26

This'll do,

Collections.sort(yourList, String.CASE_INSENSITIVE_ORDER);

this is i have tried,

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 output i got,

[Admin, Readonly, CSR, adminuser, user, customer]
[Admin, adminuser, CSR, customer, Readonly, user]
查看更多
贼婆χ
5楼-- · 2020-03-18 06:30
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());
查看更多
手持菜刀,她持情操
6楼-- · 2020-03-18 06:30

Answer is simple - big letters have lower number in ASCII. So default comparing works fine.

查看更多
倾城 Initia
7楼-- · 2020-03-18 06:37

You can use your own comparator like this to sort irrespective of case (upper / lower case)

Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2)
        {    
            return  s1.compareToIgnoreCase(s2);
        }
});
查看更多
登录 后发表回答