How do I sort objects of ArrayList by its date?

How do I sort objects of ArrayList by its date?



Here is the example How to sort the Students by their Date of birth.


       
import java.text.ParseException;
import java.text.SimpleDateFormat;
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) throws ParseException {
  SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
  List list = new ArrayList<>(
    Arrays.asList(new Student[] { new Student(1, "Hardik", format.parse("31/12/1998")),
      new Student(2, "Rohit", format.parse("30/06/1991")),
      new Student(3, "Aaryan", format.parse("05/05/1995")) }));

  System.out.println("Sort by ascending order.");
  Collections.sort(list, new ConpareByDate(ShortBy.ASC));
  System.out.println(list);
  System.out.println("Sort by descending order.");
  Collections.sort(list, new ConpareByDate(ShortBy.DES));
  System.out.println(list);
 }
}

enum ShortBy {
 ASC, DES
}

class ConpareByDate implements Comparator {

 private ShortBy sortBy;

 ConpareByDate(ShortBy sortBy) {
  this.sortBy = sortBy;
 }

 @Override
 public int compare(Student o1, Student o2) {
  if (ShortBy.ASC.equals(sortBy)) {
   return o1.getDob().compareTo(o2.getDob());
  } else if (ShortBy.DES.equals(sortBy)) {
   return o2.getDob().compareTo(o1.getDob());
  }
  return 0;
 }

}

 


Output of the program as below:

       
Sort by ascending order.
[Student [id=2, name=Rohit, dob=Sun Jun 30 00:00:00 IST 1991], Student [id=3, name=Aaryan, dob=Fri May 05 00:00:00 IST 1995], Student [id=1, name=Hardik, dob=Thu Dec 31 00:00:00 IST 1998]]
Sort by descending order.
[Student [id=1, name=Hardik, dob=Thu Dec 31 00:00:00 IST 1998], Student [id=3, name=Aaryan, dob=Fri May 05 00:00:00 IST 1995], Student [id=2, name=Rohit, dob=Sun Jun 30 00:00:00 IST 1991]]


 

Comments

Popular posts from this blog

How do I create an array of a string?

Explain briefly about POJO in Java?