One of the common interview question is ‘What are differences between Comparator and Comparable’. or ‘How will you sort collection of employee objects by its id or name’.For that we can use two interfaces.i.e. Comparator and Comparable.

The Comparator and Comparable in Java_Comparator comparabl

Java code:
For Comparable: We will create class country having attribute id and name.This class will implement Comparable interface and implement CompareTo method to sort collection of country object by id.

1.Country.java

The Comparator and Comparable in Java_Comparator comparabl_02

2.ComparableMain.java

The Comparator and Comparable in Java_Comparator comparabl_03

Output:

Before Sort by id :

Country id1Country nameChina

Country id3Country nameJapan

Country id4Country nameAmerica

Country id2Country nameBritain

After Sort  :

Country Id: 1Country name: China

Country Id: 2Country name: Britain

Country Id: 3Country name: Japan

Country Id: 4Country name: America


For Comparator: We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

1.Country.java

The Comparator and Comparable in Java_Comparator comparabl_04

2.CountrySortbyIdComparator.java

The Comparator and Comparable in Java_Comparator comparabl_05

3.ComparatorMain.java

The Comparator and Comparable in Java_Comparator comparabl_06

Output:

Before Sort by id :

Country id1Country nameChina

Country id3Country nameJapan

Country id4Country nameAmerica

Country id2Country nameBritain

After Sort by id:

Country Id: 1Country name: China

Country Id: 2Country name: Britain

Country Id: 3Country name: Japan

Country Id: 4Country name: America

After Sort by name:

Country Id: 4Country name: America

Country Id: 2Country name: Britain

Country Id: 1Country name: China

Country Id: 3Country name: Japan