简体   繁体   English

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

[英]How to sort a list of BigDecimal objects

Given the following input: 鉴于以下输入:

-100
50
0
56.6
90

I have added each value as a BigDecimal to a list. 我已将每个值作为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列表从最高到最低排序?

In your code you are only calling reverse which reverses the order of the list. 在您的代码中,您只是调用reverse来反转列表的顺序。 You need to sort the list as well, in reversed order . 您还需要按相反的顺序对列表进行排序。

This will do the trick: 这样就可以了:

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

You can use org.apache.commons.collections.list.TreeList . 您可以使用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. 然后你可以根据需要反转它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM