Java sort list by date ascending
Show DetailsWritten by Nam Ha Minh Last Updated on 17 June 2019 | Print Email In Java, it’s pretty easy to sort elements in a list collection using the Collections.sort() static utility method. This method has two forms as follows:
1. Sorting a list according to natural ordering of elementsBasically, a list can be sorted if only all of its elements are mutually comparable by implementing the Comparableinterface. If a class implements the Comparableinterface, it is considered as having natural ordering which allows objects of that class to be sorted by the Collections.sort(list) method.All basic data type wrapper classes in Java have natural ordering: String, Character, Byte, Date, Integer, Float, etc. Here are some examples:
2. Reversing sort orderBecause the sort(list) method always sorts the specified list into ascending order, so if we want to sort by descending order, we need to use the Collections.reverse(list) method in addition. For example:List3. Sorting a list whose elements of a custom typeWhat if a list contains elements of a custom type other than the pre-defined types above? Well, in that case, we have to make the class of the custom type implements the Comparableinterface. Suppose that we have a custom type called Employeeas follows:public class Employee { private String name; private int age; private int salary; public Employee(String name, int age, int salary) { this.name = name; this.age = age; this.salary = salary; } // getters and setters } If we try to sort a list whose elements of the type Employeeabove, the sort(list) method will throw a ClassCastException. Now, let’s the Employeeclass implemented the Comparable interface as follows:public class Employee implements Comparable4. Sorting a list using a ComparatorThe second form of the sort method takes a Comparator implementation that defines the ordering of elements in the list externally:Collections.sort(list, Comparator) In this case, the type of the elements need not implement the Comparable interface. This would be useful if we need to sort a list of custom objects which we cannot modify its class; or if we don’t want to rely on the natural ordering of the elements. The following code is example of a comparator that compares two employees based on their ages:package net.codejava.collections; import java.util.Comparator; /** * This comparator compares two employees by their ages. * @author www.codejava.net * */ public class EmployeeAgeComparator implements ComparatorAPI ReferencesRelated Sorting tutorials:Other Java Collections Tutorials:
Sorting the date given by the user in a day, month, year order. Sort them in ascending order and display them. Conversion_programsIn_built_functionsSorting |