How to sort a list of BigDecimal objects

25k views Asked by At

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?

3

There are 3 answers

3
Franz Becker On BEST ANSWER

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());
1
Raman Shrivastava On

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.

0
Aakash Goplani On

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