gpt4 book ai didi

java - 如何对 BigDecimal 对象列表进行排序

转载 作者:搜寻专家 更新时间:2023-10-31 19:27:29 24 4
gpt4 key购买 nike

给定以下输入:

-100
50
0
56.6
90

我已将每个值作为 BigDecimal 添加到列表中。

我希望能够从最高值到最低值对列表进行排序。

我尝试通过以下方式做到这一点:

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

List<BigDecimal> list = new ArrayList<BigDecimal>();

while(sc.hasNext()){
list.add(new BigDecimal(sc.next()));
}

Collections.reverse(list);

for(BigDecimal d : list){

System.out.println(d);
}
}

哪些输出:

90
56.6
0
50
-100

在这种情况下,50 的值应该高于 0。

考虑到十进制和非十进制值,如何正确地将 BigDecimal 列表从最高到最低排序?

最佳答案

在您的代码中,您只是调用 reverse 来反转列表的顺序。您还需要对列表进行排序,在 reversed order 中.

这样就可以了:

Collections.sort(list, Collections.reverseOrder());

关于java - 如何对 BigDecimal 对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30958788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com