BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Comparator Interface in Java

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In the last tutorial, we have seen how to sort objects of a custom class using Comparable interface. By using Comparable we can sort the objects based on any data member. For example, lets say we have an Author class has data members: Author name, book name and author age, now if we want to sort the objects based on any of the data member then we can use Comparable but what if we want to have multiple sort choices and we can sort objects based on any choice, this can be done using Comparator interface, we can create as many Comparator as we want and then we can call Collections.sort on one or more Comparator like this:

//Sorting arraylist al by Author Age
Collections.sort(al, new AuthorAgeComparator());

//Sorting arraylist al by Book Name
Collections.sort(al, new BookNameComparator());

So how does it work? To call the Collections.sort method like this, we must first need to write these Comparator classes AuthorAgeComparator and BookNameComparator, along with Author class and the main class.

Complete Comparator Example

Author.java

public class Author implements Comparable<Author> {
  String firstName; 
  String bookName; 
  int auAge; 
  Author(String first, String book, int age){ 
    this.firstName = first; 
    this.bookName = book; 
    this.auAge = age; 
  } 
  public String getFirstName() { 
    return firstName; 
  }
  public void setFirstName(String firstName) { 
    this.firstName = firstName; 
  }
  public String getBookName() { 
    return bookName; 
  }
  public void setBookName(String bookName) { 
    this.bookName = bookName; 
  }
  public int getAuAge() { 
    return auAge; 
  }
  public void setAuAge(int auAge) { 
    this.auAge = auAge; 
  } 
  @Override 
  /* 
   * When we only use Comparable, this is where we write sorting
   * logic. This method is called when we implement the Comparable
   * interface in our class and call Collections.sort()
   */ 
  public int compareTo(Author au){         
    return this.firstName.compareTo(au.firstName);   
  }
}

AuthorAgeComparator.java

import java.util.*;
class AuthorAgeComparator implements Comparator<Author>{
   public int compare(Author a1,Author a2){
     if(a1.auAge==a2.auAge)
       return 0;
   else if(a1.auAge>a2.auAge)
       return 1;
   else
       return -1;
  }
}

BookNameComparator.java

import java.util.*; 
public class BookNameComparator implements Comparator<Author>{ 
  public int compare(Author a1,Author a2){   
     return a1.bookName.compareTo(a2.bookName); 
  }  
}

SortingPgm.java

import java.util.ArrayList;  
import java.util.Collections;
public class SortingPgm{     
   public static void main(String args[]){    
     // List of objects of Author class      
     ArrayList<Author> al=new ArrayList<Author>();        
     al.add(new Author("Henry", "Tropic of Cancer",  45));
     al.add(new Author("Nalo", "Brown Girl in the Ring", 56));
     al.add(new Author("Frank", "300", 65));
     al.add(new Author("Deborah", "Sky Boys", 51));
     al.add(new Author("George R. R.", "A Song of Ice and Fire", 62));
     /*       
      * Sorting the list using Collections.sort() method, we       
      * can use this method because we have implemented the        
      * Comparable interface in our user defined class Author       
      */      
     System.out.println("Sorting by Author First Name:");      
     Collections.sort(al);        
     for(Author au: al){       
       System.out.println(au.getFirstName()+", "+au.getBookName()+", "+
           au.getAuAge());        
     } 
     /*Sorting using AuthorAgeComparator*/      
     System.out.println("Sorting by Author Age:");
     Collections.sort(al, new AuthorAgeComparator());
     for(Author au: al){       
       System.out.println(au.getFirstName()+", "+au.getBookName()+", "+
          au.getAuAge());        
     }             
     /*Sorting using BookNameComparator*/      
     System.out.println("Sorting by Book Name:");      
     Collections.sort(al, new BookNameComparator());      
     for(Author au: al){       
        System.out.println(au.getFirstName()+", "+au.getBookName()+", "+ 
           au.getAuAge());       
     }    
  }  
}  

Output:

Sorting by Author First Name:
Deborah, Sky Boys, 51
Frank, 300, 65
George R. R., A Song of Ice and Fire, 62
Henry, Tropic of Cancer, 45
Nalo, Brown Girl in the Ring, 56

Sorting by Author Age:
Henry, Tropic of Cancer, 45
Deborah, Sky Boys, 51
Nalo, Brown Girl in the Ring, 56
George R. R., A Song of Ice and Fire, 62
Frank, 300, 65

Sorting by Book Name:
Frank, 300, 65
George R. R., A Song of Ice and Fire, 62
Nalo, Brown Girl in the Ring, 56
Deborah, Sky Boys, 51
Henry, Tropic of Cancer, 45

Top Related Articles:

  1. Break statement in Java with example
  2. Multilevel inheritance in java with example
  3. How to Convert an array to ArrayList in java
  4. Java 8 features with examples
  5. How to sort ArrayList in Java

Tags: Collections

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap