The Comparator and Comparable in Java
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.
1.Country.java
2.ComparableMain.java
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
2.CountrySortbyIdComparator.java
3.ComparatorMain.java
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
转载于:https://blog.51cto.com/8841087/1403133