java 如何对 BigDecimal 对象列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30958788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a list of BigDecimal objects
提问by crmepham
Given the following input:
给定以下输入:
-100
50
0
56.6
90
I have added each value as a BigDecimal
to a list.
我已将每个值作为 a 添加BigDecimal
到列表中。
I want to be able to sort the list from highest to lowest value.
我希望能够从最高值到最低值对列表进行排序。
I have attempted to do this in the following way:
我试图通过以下方式做到这一点:
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);
}
}
Which outputs:
哪些输出:
90
56.6
0
50
-100
In this instance 50 should be a higher value than 0.
在这种情况下,50 应该是比 0 更高的值。
How can I correctly sort a BigDecimal list from highest to lowest taking into account decimal and non decimal values?
考虑到十进制和非十进制值,如何正确地从高到低对 BigDecimal 列表进行排序?
回答by Franz Becker
In your code you are only calling reverse which reverses the order of the list. You need to sort the list as well, in reversed order.
在您的代码中,您只调用 reverse 来反转列表的顺序。您还需要以相反的顺序对列表进行排序。
This will do the trick:
这将解决问题:
Collections.sort(list, Collections.reverseOrder());
回答by Raman Shrivastava
You can use org.apache.commons.collections.list.TreeList
. No need to sort. It will keep inserted objects in sorted order. Then you can just reverse it if you want.
您可以使用org.apache.commons.collections.list.TreeList
. 无需排序。它将按排序顺序保留插入的对象。然后,如果您愿意,您可以将其反转。
回答by Aakash Goplani
You can try this one, it worked for me:
你可以试试这个,它对我有用:
package HackerRank;
import java.util.*;
import java.math.*;
class Sorting
{
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
TreeSet<BigDecimal> list = new TreeSet<BigDecimal>();
int testCase = sc.nextInt();
while(testCase-- > 0)
list.add(new BigDecimal(sc.next()));
System.out.println(list); //ascending order
System.out.println(list.descendingSet()); //descending order
}
}