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

Java中使用stream.sorted()对带数字后缀的字符串排序异常问题

问题分析与解决方案

Hey there! Let's break down why your sorted result isn't turning out like you expected.

问题根源

Right now, you're comparing the substrings after "-" as plain text, which uses lexicographical (dictionary) order instead of numeric order. That's why "15" gets sorted before "4" — because the character '1' comes before '4' in the dictionary, even though 15 is a bigger number.

修复代码

You need to convert those substrings into integers first, then compare their numeric values instead. Here's how to adjust your sorted logic:

}).map(c -> { 
    System.out.println(c); 
    return c; 
}).distinct() 
.sorted((c1, c2) -> {
    // Extract the numeric part after "-" and convert to integer
    int num1 = Integer.parseInt(c1.substring(c1.indexOf("-") + 1));
    int num2 = Integer.parseInt(c2.substring(c2.indexOf("-") + 1));
    // Compare the integers directly
    return Integer.compare(num1, num2);
})
.collect(Collectors.toList());

为什么这样有效?

  • c1.indexOf("-") + 1 skips the "-" character to get the start of the numeric part
  • Integer.parseInt(...) converts that substring into an actual integer value
  • Integer.compare(num1, num2) does a proper numeric comparison, so 4 < 9 < 15 like you expect

With this change, your final list will be [sg-1, sg-4, sg-9, sg-15] — exactly what you wanted!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:51:22