我想通过降低字符串长度来排序一个immutableList的副本。我必须在Java 8下支持API。
我尝试了这个基本代码,但仍然是相反的顺序
ImmutableList<String> possibleTexts = ImmutableList.of("aa", "bbbbbb");
final List<String> mutableList = new ArrayList<>(possibleTexts);
Collections.sort(mutableList, (s1, s2) -> Math.abs(s1.length() - s2.length()));
但是mutableList是"aa", "bbbbbb"
代替"bbbbbb","aa"
你的输出是你期待什么,因为对面Math.abs(s1.length() - s2.length())
的回报4
两个|2 - 6|
和|6 - 2|
。
的文档Collections#sort
还指出以下内容:
这样的排序保证是稳定的:相等的元素不会由于排序而重新排序。
要解决您的问题,您可以删除Math#abs
并交换比较(a的长度String
不能为负,因此不会发生上溢/下溢):
Collections.sort(mutableList, (s1, s2) -> s2.length() - s1.length());
但是,我建议List#sort
与Comparator#comparingInt
和一起使用Comparator#reversed
,因为它比您当前的代码段更具可读性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句