简体   繁体   中英

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.

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.

How can I correctly sort a BigDecimal list from highest to lowest taking into account decimal and non decimal values?

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 .

This will do the trick:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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