Monday, May 12, 2014

How to Sort List of Custom Objects in Java ?


This blog explains about sorting list of custom objects in Java

- Define a Custom Java class, In this example, I want to sort all the EmployeeDTO objects based on salary
- Implement 'Comprable' Interface
- Override 'compareTo' method as shown below
- Perform Collections.sort(List) method as shown below, This will internally invoke compareTo() method and sort based on compareTo() implementation.

       

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class EmployeeDTO implements Comparable {
    public EmployeeDTO() {
        super();
    }
    private String firstName;
    private String lastName;
    private int sal;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setSal(int sal) {
        this.sal = sal;
    }

    public int getSal() {
        return sal;
    }

    /**
     *Override compareTo() method
     * @param employee
     * @return
     */
    public int compareTo(EmployeeDTO employee) {
        // Ascending Order
        return this.sal - employee.getSal();
        // Descending Order
        //return employee.getSal()-this.sal;


    }
 }
       
 

- Test above code as shown below, Here I am randomly generating salary value using 'Random' Generator class.
       

      public static void main(String[] args) {
        EmployeeDTO dto = null;
        // Random Number Generator
        Random randomGenerator = new Random();
        List list = new ArrayList();
        for (int i = 0; i < 5; i++) {
            int sal = randomGenerator.nextInt(100);
            dto = new EmployeeDTO();
            dto.setFirstName("FirstName" + sal);
            dto.setLastName("LastName" + sal);
            dto.setSal(sal);
            list.add(dto);
        }
        System.out.println(" Before Sort : ");
        Iterator it = list.iterator();
        while (it.hasNext()) {
            dto = (EmployeeDTO)it.next();
            System.out.println(" First Name : " + dto.getFirstName());
            System.out.println(" Last Name : " + dto.getLastName());
            System.out.println(" Sal : " + dto.getSal());
        }
        // Perform Sorting
        Collections.sort(list);
        System.out.println(" After Sort : ");
        it = list.iterator();
        while (it.hasNext()) {
            dto = (EmployeeDTO)it.next();
            System.out.println(" First Name : " + dto.getFirstName());
            System.out.println(" Last Name : " + dto.getLastName());
            System.out.println(" Sal : " + dto.getSal());
        }
    }
       
 


- We can achieve same by using 'Comparator' Interface
- Write a custom comparator class as shown below
       

  package com.fm.recruitment.model.util;

import java.util.Comparator;


public class SalComparator implements Comparator {

    public SalComparator(){
        super();
    }
    public int compare(EmployeeDTO emp1, EmployeeDTO emp2) {
        int flag = emp1.getSal() - emp2.getSal();
        return flag;
    }
}

       
 

- Follow below code to sort using above comparator
Collections.sort(list,new SalComparator());