How to sort a list of BigDecimal objects

Given the following input:

-100 50 0 56.6 90 

I added each value as BigDecimal to the list.

I want to sort the list from highest to lowest.

I tried to do it as follows:

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

What outputs:

 90 56.6 0 50 -100 

In this case, 50 should be a higher value than 0.

How to correctly sort the BigDecimal list from highest to lowest, taking into account decimal and decimal values?

+5
source share
3 answers

In your code, you only call the reverse, which changes the order of the list. You also need to sort the list in reverse order .

This will do the trick:

 Collections.sort(list, Collections.reverseOrder()); 
+8
source

You can use org.apache.commons.collections.list.TreeList . No need to sort. It will contain the inserted objects in sorted order. Then you can just cancel it if you want.

0
source

You can try this, 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 } } 
0
source

All Articles