Simple way to sort strings in the (case sensitive) alphabetical order

前端 未结 5 2044
生来不讨喜
生来不讨喜 2020-11-27 19:56

I need to sort list of strings in the alphabetical order:

List list = new ArrayList();
list.add(\"development\");
list.add(\"Development\");
li         


        
5条回答
  •  忘掉有多难
    2020-11-27 20:45

    If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

    private static Comparator ALPHABETICAL_ORDER = new Comparator() {
        public int compare(String str1, String str2) {
            int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
            if (res == 0) {
                res = str1.compareTo(str2);
            }
            return res;
        }
    };
    
    Collections.sort(list, ALPHABETICAL_ORDER);
    

    And I think it is just as easy to understand and code ...

    The last 4 lines of the method can written more concisely as follows:

            return (res != 0) ? res : str1.compareTo(str2);
    

提交回复
热议问题