You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串按长度+大小写敏感排序异常问题求助

Fixing the String Sort Order Issue

Got it, let's get this sorted (pun intended!) for you. Your current code handles length-based sorting perfectly, but the case-sensitive ordering is reversed from what you need. Let's break down why this happens and fix it step by step.

Why the Current Code Fails

The default String.compareTo() method uses Unicode code points for comparison. Since uppercase letters have lower Unicode values than their lowercase counterparts (e.g., 'A' = 65, 'a' = 97), this puts uppercase strings ahead of lowercase ones when lengths are equal. That's why you're seeing [a, b, e, fe, ABC, ABc, Abc, abc] instead of your desired order.

The Solution: Custom Case-Priority Comparison

We need to tweak the Comparator to prioritize lowercase characters over uppercase ones when strings have the same length. Here's the adjusted, working code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class StringSortExample {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        stringList.add("a");
        stringList.add("abc");
        stringList.add("b");
        stringList.add("fe");
        stringList.add("e");
        stringList.add("ABC");
        stringList.add("Abc");
        stringList.add("ABc");
        
        System.out.print("Before Sort:");
        System.out.println(stringList);
        
        Collections.sort(stringList, new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
                // First sort by string length (cleaner than manual if-else checks)
                int lengthComparison = Integer.compare(o1.length(), o2.length());
                if (lengthComparison != 0) {
                    return lengthComparison;
                }
                
                // For same-length strings, enforce lowercase-first priority
                for (int i = 0; i < o1.length(); i++) {
                    char c1 = o1.charAt(i);
                    char c2 = o2.charAt(i);
                    
                    if (c1 == c2) {
                        continue;
                    }
                    
                    boolean isC1Lower = Character.isLowerCase(c1);
                    boolean isC2Lower = Character.isLowerCase(c2);
                    
                    // If one character is lowercase and the other uppercase, put lowercase first
                    if (isC1Lower && !isC2Lower) {
                        return -1;
                    } else if (!isC1Lower && isC2Lower) {
                        return 1;
                    }
                    
                    // If both are same case, use natural character order
                    return Character.compare(c1, c2);
                }
                
                // All characters are identical
                return 0;
            }
        });
        
        System.out.print("After Sort :");
        System.out.println(stringList);
    }
}

How This Works

  1. Length Sort: We use Integer.compare() to compare string lengths—this is a more concise and readable alternative to manual if-else checks.
  2. Custom Case Sort:
    • For strings with the same length, we iterate through each character pair.
    • If one character is lowercase and the other is uppercase, the string containing the lowercase character moves to the front.
    • If both characters are the same case (both uppercase or both lowercase), we use standard character comparison to maintain natural order (e.g., "b" comes after "a").

Expected Output

When you run this code, you'll get exactly the order you wanted:

Before Sort:[a, abc, b, fe, e, ABC, Abc, ABc]
After Sort :[a, b, e, fe, abc, Abc, ABc, ABC]

内容的提问来源于stack exchange,提问作者slider_rahul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:47:52