Java: How do you sort an ArrayList in descending order?
Java: How do you sort an ArrayList in descending order?
There can be 2 scenarios to shot the ArrayList.
(1) Sort the ArrayList which contains the in build types like Long, String,Integer ect.
(2) Sort ArrayList which contains the custom type. Let's say List of Student class and you want to sort by name.
See the code for both scenario.
(1) Sort List of inbuilt types
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListSort1 {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList(new Long[] { 50l, 4l, 10l, 1l, 2l, 3l }));
System.out.println("Before Short");
System.out.println(list);
System.out.println("After Short");
list.sort(Collections.reverseOrder());
System.out.println(list);
}
}
You can see the output as below:
Before Short
[50, 4, 10, 1, 2, 3]
After Short
[50, 10, 4, 3, 2, 1]
Here you can see that We are sorting the Long type by descending.
(2) Sort List of custom types
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ArrayListSort2 {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays
.asList(new Student[] { new Student(1, "Hardik"), new Student(2, "Rohit"), new Student(3, "Aaryan") }));
System.out.println("Sort by ascending order.");
Collections.sort(list,new ConpareByName(ShortBy.ASC));
System.out.println(list);
System.out.println("Sort by descending order.");
Collections.sort(list,new ConpareByName(ShortBy.DES));
System.out.println(list);
}
}
enum ShortBy {
ASC,DES
}
class ConpareByName implements Comparator {
private ShortBy sortBy;
ConpareByName(ShortBy sortBy) {
this.sortBy = sortBy;
}
@Override
public int compare(Student o1, Student o2) {
if(ShortBy.ASC.equals(sortBy) ){
return o1.getName().compareTo(o2.getName());
}else if(ShortBy.DES.equals(sortBy) ){
return o2.getName().compareTo(o1.getName());
}
return 0;
}
}
See the output as below :
Sort by ascending order.
[Student [id=3, name=Aaryan], Student [id=1, name=Hardik], Student [id=2, name=Rohit]]
Sort by descending order.
[Student [id=2, name=Rohit], Student [id=1, name=Hardik], Student [id=3, name=Aaryan]]
Here you can see that we have custom class with two fields id and name. We have list of 3 students and want to sort by ascending and descending both. So I have created one class which implements Compactor interface and do the sorting.
Comments
Post a Comment