【问题标题】:Sort a String array in java (special way)在java中对String数组进行排序(特殊方式)
【发布时间】:2016-01-18 10:40:52
【问题描述】:

我在这样做时遇到了问题,因为我需要以这种方式对其进行排序:

之前:

{aAbB, abBA, AaBb}

之后:

{AaBb, aAbB, abBA}

这个想法是在它的小写版本之前对一个大写字母进行排序,并且对每个字母进行排序。 我实际上正在使用西班牙语的 Collat​​or('ñ' 的问题)并将其强度设置为 PRIMARY,这样我就可以比较两个单词是否相等而无需关心大写字母。

【问题讨论】:

    标签: java arrays sorting uppercase lowercase


    【解决方案1】:

    这会产生所需的结果。

    Arrays.sort(stringArray) 
    

    【讨论】:

    • 虽然这段代码可以回答这个问题,但最好在不介绍其他代码的情况下解释它是如何解决问题的,以及为什么要使用它。从长远来看,纯代码的答案没有用处。
    【解决方案2】:

    只要做:

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

    灵感来自:Simple way to sort strings in the (case sensitive) alphabetical order

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-20
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多