Core java: Sorting List elements using Comparator example

Comparator example using Map and HashMap and List: adding employees and displaying employees in sorting order. Here i am providing download link for this example. If free hosting site deletes that file drop your mail id to get this example.

download Sorting List of Ojbects using Comparator example open it with eclipse and execute main method




Employee.java

package domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();

}


EmployeeImpl.java

package domain.impl;

import utils.EmployeeIO;
import domain.Employee;

public class EmployeeImpl extends EmployeeIO implements Employee{
    
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;
  
    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if("CEO".equalsIgnoreCase(designation)){
            setPriority(1);
        }else if("MD".equalsIgnoreCase(designation)){
            setPriority(2);
        }else if("HR".equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("EmployeeImpl [id=");
        buffer.append(id);
        buffer.append(", firstName=");
        buffer.append(firstName);
        buffer.append(", lastName=");
        buffer.append(lastName);
        buffer.append(", email=");
        buffer.append(email);
        buffer.append(", priority=");
        buffer.append(priority);
        buffer.append(", designation=");
        buffer.append(designation);
        buffer.append("]");
        return buffer.toString();
    }
   
    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            && this.firstName.equalsIgnoreCase( employee.getFirstName())
            && this.lastName.equalsIgnoreCase( employee.getLastName())
            && this.email.equalsIgnoreCase( employee.getEmail())
            && this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
        if(this.hashCode()== employee.hashCode())return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append("\t");
        buffer.append(this.getFirstName());
        buffer.append("\t");
        buffer.append(this.getLastName());
        buffer.append("\t");
        buffer.append(this.getEmail());
        buffer.append("\t");
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}


EmployeeService.java

package service;

import java.util.List;

import domain.Employee;

public interface EmployeeService {

    List<Employee> getAll();

    void addEmployee(Employee employee);
 
    List<Employee> getAll(String sortBy);

}

EmployeeServiceImpl.java

package service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import service.EmployeeService;
import domain.Employee;

public class EmployeeServiceImpl implements EmployeeService {
    private List<Employee> employees = new ArrayList<Employee>();

    private static Map<String, Comparator<Employee>> 
   COMPARATORS = new HashMap<String, Comparator<Employee>>();

    static {
        COMPARATORS.put("firstName", new Comparator<Employee>() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getFirstName().compareTo(emp2.getFirstName());
            }
        });
        COMPARATORS.put("lastName", new Comparator<Employee>() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getLastName().compareTo(emp2.getLastName());
            }
        });
        COMPARATORS.put("email", new Comparator<Employee>() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getEmail().compareTo(emp2.getEmail());
            }
        });
        COMPARATORS.put("designation", new Comparator<Employee>() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getPriority() - emp2.getPriority();
            }
        });
        COMPARATORS.put("id", new Comparator<Employee>() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getId() - emp2.getId();
            }
        });
    }

   @Override
    public List<Employee> getAll() {
        List<Employee> employees = new ArrayList<Employee>(this.employees);
        return Collections.unmodifiableList(employees);
    }

    @Override
    public List<Employee> getAll(String sortBy) {
        Comparator<Employee> comparator = COMPARATORS.get(sortBy);
        if (comparator == null) {
            throw new IllegalArgumentException("Invalid sortBy option: "
                    + sortBy);
        }
        List<Employee> sortedEmployees = new ArrayList<Employee>(this.employees);
        Collections.sort(sortedEmployees, comparator);
        return sortedEmployees;
    }

    @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println("Employee already exists");
  } else {
   this.employees.add(employee);
  }
 }
}


EmployeeIO.java

package utils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import domain.Employee;
import domain.impl.EmployeeImpl;

public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt("Enter Id :"));
  employee.setFirstName(KeyBoard.read("Enter First Name :"));
  employee.setLastName(KeyBoard.read("Enter Last Name :"));
  employee.setEmail(KeyBoard.read("Enter Email :"));
  employee.setDesignation(KeyBoard.read("Enter Designation :"));
  return employee;
 }

 public static void out(List<Employee> employees) {
  StringBuilder builder = new StringBuilder();
  builder.append("Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n");
  for (int i = 0; i < employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append("\n");
  }
  System.out.println(builder);
 }
 
 public static String sortOptions(){
        Map<String, String> sortOptions = 
            new LinkedHashMap<String, String>();
        sortOptions.put("firstName", "Sort by First Name");
        sortOptions.put("lastName", "Sort by Last Name");
        sortOptions.put("email", "Sort by Email");
        sortOptions.put("designation", "Sort by Designation");
        sortOptions.put("id", "Sort by id");
        return options(sortOptions);
    }
    
    public static String options(Map<String, String> options) {
        StringBuilder builder = new StringBuilder();
        Map<Integer, String> myOptions = new HashMap<Integer,String>();
        
        Set<Entry<String,String>> entrySet = options.entrySet();
        int i = 0;
        for (Entry<String, String> entry : entrySet) {
            builder.append(++i).append(". ").append(entry.getValue());
            builder.append("\n");
            myOptions.put(i, entry.getKey());
        }
        System.out.print(builder.toString());
        int option = KeyBoard.readInt("Enter your Choice:");
        return myOptions.get(option);
    }
   
}


KeyBoard.java
package utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println("Invalid Number");
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

EmployeeMain.java
package main;

import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
import utils.EmployeeIO;
import utils.KeyBoard;
import domain.Employee;

public class EmployeeMain {

    public static void main(String[] args){
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            empService.addEmployee(employee);
            option = KeyBoard.readInt(
                    "Do you want add another employee(1/0) :");
            
        } while(option == 1);
        System.out.println("Reading from file");
        EmployeeIO.out(empService.getAll());
        String sortBy = EmployeeIO.sortOptions();
        try{
            EmployeeIO.out(empService.getAll(sortBy));
        }catch(IllegalArgumentException e){
            System.out.println("Invalid sort option: "+sortBy);
        }
    }
}

Output of the programe
Enter Id :1
Enter First Name :eeee
Enter Last Name :ffff
Enter Email :eeff@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :bbbb
Invalid Number
Enter Id :6
Enter First Name :bbbb
Enter Last Name :dddd
Enter Email :ddbb@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :hhhh
Enter Last Name :llll
Enter Email :hlhl@gmail.com
Enter Designation :ceo
Do you want add another employee(1/0) :1
Enter Id :8
Enter First Name :kkkkk
Enter Last Name :aaaa
Enter Email :kaka@gmail.com
Enter Designation :pm
Do you want add another employee(1/0) :0
Reading from file
Id First Name Last Name Email Designation
1 eeee ffff eeff@gmail.com developer
6 bbbb dddd ddbb@gmail.com hr
3 hhhh llll hlhl@gmail.com ceo
8 kkkkk aaaa kaka@gmail.com pm

1. Sort by First Name
2. Sort by Last Name
3. Sort by Email
4. Sort by Designation
5. Sort by id
Enter your Choice:2
Id First Name Last Name Email Designation
8 kkkkk aaaa kaka@gmail.com pm
6 bbbb dddd ddbb@gmail.com hr
1 eeee ffff eeff@gmail.com developer
3 hhhh llll hlhl@gmail.com ceo




Categories: