作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
给定以下输入:
-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/
我是一名优秀的程序员,十分优秀!