Array List of String Sorting Method

后端 未结 6 517
小蘑菇
小蘑菇 2021-01-12 10:39

i have an Array List with Following values

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

when i used

Collections.s         


        
相关标签:
6条回答
  • 2021-01-12 10:48
    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());
    
    0 讨论(0)
  • 2021-01-12 10:55

    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);
            }
    });
    
    0 讨论(0)
  • 2021-01-12 10:55
    Collections.sort(ArrayList, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.toLowerCase().compareTo(s2.toLowerCase());
            }
        });
    
    0 讨论(0)
  • 2021-01-12 10:56

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

    0 讨论(0)
  • 2021-01-12 11:06

    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]
    
    0 讨论(0)
  • 2021-01-12 11:06

    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.

    0 讨论(0)
提交回复
热议问题