Skip to main content

Comparator Vs Comarable

Comparable Interface

Comparable is an interface in java, which has only comparTo (Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparable is preferred.

1. Having provision of modifying the User defined object to implement the Comparable interface. (Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined object by one Member field in their natural sorting order.
3. Comparable provides only one Sorting for an Object.

Our String and Wrapper Classes like Integer, Double, Long, BigDecimal etc. are override this compareTo method by implementing the Comparable Interface.


For example,
To sort the Bank Accounts  based on the amount it contains.

1. Create Account pojo with all the member fields including amount.
2. Implement the Account pojo with Comparable interface.
3. Override the compareTo(Object obj) method from Comparable interface. (Refer following code snippet)

Account POJO

package com.sbs.sort;

import java.math.BigDecimal;

public class Account implements Comparable<Account>{

    private BigDecimal ammount;
    private Long accountNumber;
    private String accountHolderName;
   
    public Account(BigDecimal ammount, Long accountNumber,
            String accountHolderName) {
        super();
        this.ammount = ammount;
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
    }

    public BigDecimal getAmmount() {
        return ammount;
    }

    public void setAmmount(BigDecimal ammount) {
        this.ammount = ammount;
    }

    public Long getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(Long accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    @Override
    public int compareTo(Account o) {
        return this.ammount.compareTo(o.getAmmount());
    }
}

ComparableSortTest 

package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableSortTest {

    public ComparableSortTest() {
    }
    public static List<Account> accountsList = new ArrayList<Account>();
   
    static
    {
        accountsList.add(new Account(new BigDecimal("200000"),10010l,"Bhargava Surimenu"));
        accountsList.add(new Account(new BigDecimal("20000"),100102l,"Satya Surimenu"));
        accountsList.add(new Account(new BigDecimal("100000"),100104l,"Hemachandra Surimenu"));
        accountsList.add(new Account(new BigDecimal("600000"),100106l,"Neha Surimenu"));
        accountsList.add(new Account(new BigDecimal("30000"),100108l,"Veeru Surimenu"));
        accountsList.add(new Account(new BigDecimal("700000"),100109l,"Venky Surimenu"));
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Accounts List Before Sort ------");
        System.out.println("Account   "+"Ammount");
        for(Account account:accountsList)
            System.out.println(account.getAccountNumber()+"   "+
                    account.getAmmount());
       
        //Sort
        Collections.sort(accountsList);
       
        System.out.println("----- Accounts List After Sorting ------");
       
        System.out.println("Account   "+"Ammount");
            for(Account sAccount:accountsList)
                System.out.println(sAccount.getAccountNumber()+"   "+
                        sAccount.getAmmount());
    }
}



Comparator Interface

Comparator is an interface in java, which has only compare(Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparator is preferred.

1. Having no provision of modifying the User defined object
(Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined objects by various member fields in their natural sorting order.
3. Comparator interface provides multiple comparators (Sortings)for an Object.


For example,
To sort the Employee based on the employee number it contains.

1. Create Employee pojo with all the member fields including amount.
2. Create a Employe Comparator and Implement the with Comparator interface.
3. Override the compare(Object obj) method from Comparator interface. (Refer following code snippet).
4. Pass the employee Comparator as argument to the Sort method.

Employee 

package com.sbs.sort;

import java.math.BigDecimal;


public class Employee {

    public Employee() {
       
    }

   
    public Employee(String name,String number, BigDecimal salary) {
        super();
        this.name = name;
        this.number = number;
        this.salary = salary;
    }


    private String name;
    private String number;
    private BigDecimal salary;
   
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
   
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public BigDecimal getSalary() {
        return salary;
    }
    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
   
   
}

EmpComparator 

package com.sbs.sort;

import java.util.Comparator;

public class EmpComparator implements Comparator<Employee>{

     public EmpComparator() {
       
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        return (emp1).getNumber().compareTo(emp2.getNumber());
    }
}


ComparatorSortTest
 
package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorSortTest {

    public ComparatorSortTest() {
       
    }
   
    public static List<Employee> employeeList = new ArrayList<Employee>();
    static
    {   
       
        employeeList.add(new Employee("Bhargava Surimenu","SBS101",new BigDecimal("1000")));
        employeeList.add(new Employee("Satya Surimenu","SBS108",new BigDecimal("2000")));
        employeeList.add(new Employee("Hemachandra Surimenu","SBS106",new BigDecimal("6000")));
        employeeList.add(new Employee("Satya Surimenu","SBS105",new BigDecimal("7000")));
        employeeList.add(new Employee("Neha Surimenu","SBS107",new BigDecimal("8000")));
        employeeList.add(new Employee("Veeru Surimenu","SBS102",new BigDecimal("3000")));
        employeeList.add(new Employee("Venky Surimenu","SBS104",new BigDecimal("1000")));
       
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Employees List Before Sort ------");
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
       
        //Passing EmpComparator as argument
        Collections.sort(employeeList,new EmpComparator());
       
        System.out.println("----- Employees List After Sorting ------");
       
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
    }
}

Comments

Popular posts from this blog

NO SQL Types and vendors in market

NO SQL

KEY - VALUE Store  - Similar to a  MAP.
   e.g. Dynamo DB or REDIS

DOCUMENT Sore  - Similar to KEY-VALUE, value can be JSON/XML and key will be unqiuely idnetified this document.
   e.g. Coutch DB or mongoDB.

Column Store - Multi timentional table, identifying data with row and column numbers.
  e.g.  Cassandra or Apache HBase

Graph Store - Store relation between nodes (record entities). It has better transaction management
e.g. Neo4J and Orient DB.




Spring Reactive Stack