
Hi
how to sort list of element containing a data object like date of birth of employee. display employee in youngest first and oldest last , using one of the collection class for sorting.

Here is an example that stores the employee information into the hashmap and display the data according to the date of birth.
import java.util.*;
import java.text.*;
class Employee{
String name;
String address;
Date d;
Employee(String name,String address,Date d){
this.name=name;
this.address=address;
this.d=d;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public Date getDate(){
return d;
}
}
class BirthDateComparator implements Comparator<Employee> {
public int compare(Employee p, Employee q) {
if (p.getDate().before(q.getDate())) {
return +1;
} else if (p.getDate().after(q.getDate())) {
return -1;
} else {
return 0;
}
}
}
public class EmployeeDateInAscendingOrder{
public static void main(String[] args) throws Exception{
List<Employee> list = new ArrayList<Employee>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
list.add(new Employee("Victor","Delhi",28000));
list.add(new Employee("Jennie","Mumbai",22000));
list.add(new Employee("John","Chennai",40000));
list.add(new Employee("Daniel","Kolkata",25000));
list.add(new Employee("Angelina","Pune",20000));
System.out.println("Youngest to Oldest...... ");
Collections.sort(list,new BirthDateComparator());
for(Employee data: list){
System.out.println(data.getName()+"\t"+data.getAddress()+"\t"+sdf.format(data.getDate()));
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.