AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



java-collection: How to sort a List of objects by their date of birth?

Please explain How to sort a List of objects by their date of birth.

java x 211
collection x 52
Posted On : 2016-05-08 22:37:33.0
profile Mantu Kumar - anyforum.in Mantu Kumar
8200
up-rate
1
down-rate

Answers


Date in java internally implements comparable interface. So we can simply write DateComparator class like below:

DateComparator.java:
-----------------------------------------------------
import java.util.Comparator;

public class DateComparator implements Comparator<Employee>{

@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
return o1.getDob().compareTo(o2.getDob());
}

}


Employee.java:
-----------------------------------------------
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


public class Employee {
private int id;
private Date dob;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public static void main(String[] args) {
try{
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
Employee e1=new Employee();
e1.setId(1);
e1.setDob(sdf.parse("12/02/2016"));

Employee e2=new Employee();
e2.setId(2);
e2.setDob(sdf.parse("02/01/2002"));

Employee e3=new Employee();
e3.setId(3);
e3.setDob(sdf.parse("01/12/2015"));

List<Employee> list=new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);

Collections.sort(list,new DateComparator());//sorting the objects by date of birth

System.out.println("Sorted List");

for(Employee e:list){
System.out.println("ID "+e.getId()+" & DOB: "+e.getDob());
}
}catch (Exception e) {
System.out.println(e.getMessage());
// TODO: handle exception
}
}
}


Note:
--------------------------
If you want to change the order of sorting, just change the order of object in DateComparator
return o2.getDob().compareTo(o1.getDob());

Posted On : 2016-05-08 23:40:36
Satisfied : 1 Yes  1 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188241268
Reply This Thread
up-rate
4
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in