Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
crmepham Avatar asked Jun 20 '15 20:06

crmepham


Video Answer


1 Answers

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());
like image 88
Franz Becker Avatar answered Sep 28 '22 00:09

Franz Becker