Java Comparator Interface

Java Comparator interface belongs to java.util package.

Comparator interface allows us to sort collection of custom class objects. Comparator interface allows us the capability to sort collection with the different values at the same time which comparable doesn’t allow. For example, in Student class if we have different name, id, branch fields and we want to sort collection with all at the same time. This capability only allows by Comparator but not by comparable.

Sorting logic resides in separate class other than bean class in case of comparator interface. The process is totally reverse of comparable interface where sorting logic resides in the bean class itself.

Example:

OUTPUT:
Before Sorting = [Student{id=1, name=’Saurabh’, branch=’EN’}, Student{id=2, name=’Prabjot’, branch=’IT’}, Student{id=3, name=’Nitin’, branch=’ECE’}]
Sorting on ‘name’ = [Student{id=3, name=’Nitin’, branch=’ECE’}, Student{id=2, name=’Prabjot’, branch=’IT’}, Student{id=1, name=’Saurabh’, branch=’EN’}]
Sorting on ‘id’ = [Student{id=1, name=’Saurabh’, branch=’EN’}, Student{id=2, name=’Prabjot’, branch=’IT’}, Student{id=3, name=’Nitin’, branch=’ECE’}]

Difference Between Comparable and Comparator

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan