如何对 List/ArrayList 进行排序?

新手上路,请多包涵

我在 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

原文由 Himanshu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 472
2 个回答
Collections.sort(testList);
Collections.reverse(testList);

那会做你想做的。请记住导入 Collections 不过!

这是 Collections 的文档

原文由 tckmn 发布,翻译遵循 CC BY-SA 4.0 许可协议

降序:

 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;
    }
});

原文由 최봉재 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题