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("-") + 1skips the "-" character to get the start of the numeric partInteger.parseInt(...)converts that substring into an actual integer valueInteger.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
相关产品推荐
相关产品推荐

