Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an ArrayList?

I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List<Double> testList = new ArrayList();  testList.add(0.5); testList.add(0.2); testList.add(0.9); testList.add(0.1); testList.add(0.1); testList.add(0.1); testList.add(0.54); testList.add(0.71); testList.add(0.71); testList.add(0.71); testList.add(0.92); testList.add(0.12); testList.add(0.65); testList.add(0.34); testList.add(0.62); 

The out put should be like this

0.92 0.9 0.71 0.71 0.71 0.65 0.62 0.54 0.5 0.34 0.2 0.12 0.1 0.1 0.1 
like image 877
Himanshu Avatar asked Apr 27 '13 12:04

Himanshu


People also ask

How do you sort two Arraylists?

An ArrayList can be sorted in two ways ascending and descending order. The collection class provides two methods for sorting ArrayList. sort() and reverseOrder() for ascending and descending order respectively.

How do you sort an ArrayList in Java 8?

There are multiple ways to sort a list in Java 8, for example, you can get a stream from the List and then use the sorted() method of Stream class to sort a list like ArrayList, LinkedList, or Vector and then convert back it to List. Alternatively, you can use the Collections. sort() method to sort the list.


2 Answers

Collections.sort(testList); Collections.reverse(testList); 

That will do what you want. Remember to import Collections though!

Here is the documentation for Collections.

like image 117
tckmn Avatar answered Oct 02 '22 11:10

tckmn


Descending:

Collections.sort(mArrayList, new Comparator<CustomData>() {     @Override     public int compare(CustomData lhs, CustomData rhs) {         // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending         return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;     } }); 
like image 35
최봉재 Avatar answered Oct 02 '22 12:10

최봉재