本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
我在Java中有一个列表,我想按降序对ArrayList进行排序。
输入ArrayList如下:
List<Double> testList = new ArrayList();
testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);
复制代码
输出应该是这样的
0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1
复制代码
回答1:
Java的Collections类提供了排序的sort函数,不过由于你要求降序排列,因此通过reverse反转函数将数组翻转过来
Collections.sort(testList);
Collections.reverse(testList);
复制代码
请记住要导入Collections!
回答2:
上面的回答需要调用两个方法,而且不具备拓展性,可以考虑自行定义Comparator来使数组按照你的意愿来排序。
Collections.sort(mArrayList, new Comparator<CustomData>() {
@Override
public int compare(CustomData lhs, CustomData rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
}
});
复制代码
回答3:
对于题主给出的示例数据,可以利用Java 8特性得到以下代码:
List<Double> testList = new ArrayList();
testList.sort(Comparator.naturalOrder());
复制代码
同时也可以进行拓展,比如说如果对ArrayList里面Object的某个字段升序排序
testList.sort(Comparator.comparing(ClassName::getFieldName));
复制代码
也可以对ArrayList里面Object的某个字段降序排序
testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());
复制代码
或者是
testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END