我有例如 sg-1、sg-5、sg-13、sg-6 等元素列表,我需要按数字对它们进行排序。 我的代码部分是:
}).map(c -> {
System.out.println(c);
return c;
}).distinct()
.sorted((c1, c2) -> c1.substring(c1.indexOf("-"), c1.length())
.compareTo(c2.substring(c2.indexOf("-"), c2.length())))
.collect(Collectors.toList());
系统输出打印 sg-1 sg-1 sg-1 sg-9 sg-1 sg-4 sg-15 sg-1 sg-1 sg-1 sg-1
但最后我得到 [sg-1, sg-15, sg-4, sg-9] 但它必须是 [sg-1, sg-4, sg-9, sg-15] 如何对它们进行排序,请帮助我:)
最佳答案
您做错的第一件事是您按字典顺序比较字符串,而不是您可能期望的整数。
其次,即使您将 c1.substring(c1.indexOf("-"), c1.length())
转换为整数,然后进行比较,您仍然会得到不正确的结果。
这是为什么?
这是因为c1.substring(c1.indexOf("-"), c1.length())
,substring的第一个参数是包含的,这意味着你总是会提取负数。
解决方法:
- 您实际上需要比较整数而不是字符串。
- substring 的第一个参数实际上应该是
c1.indexOf("-") + 1
,在“-”之后开始。
List<String> result = list.stream()
.distinct()
.sorted(Comparator.comparingInt(s ->
Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()))))
.collect(Collectors.toList());
顺便说一句,不要使用 map
来执行调试工作,而是使用 peek .
List<String> result = list.stream()
.peek(System.out::println)
.distinct()
.sorted(Comparator.comparingInt(s ->
Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()))))
.collect(Collectors.toList());
关于java - 在 Java 中使用 stream.sorted() 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801967/