Can we use Comparator with list in Java?



Yes, we can use comparator with a list of objects in Java. Comparator helps in creating custom comparison. For example, if we want to sort a student by roll no or by name then we can create comparators like rollNoComparator and nameComparator by implmenting the comparator interface.

class RollNoComparator implements Comparator<Student>{
   @Override
   public int compare(Student s1, Student s2) {
      return s1.getRollNo() - s2.getRollNo();
   }
}
class NameComparator implements Comparator<Student>{
   @Override
   public int compare(Student s1, Student s2) {
      return s1.getName().compareTo(s2.getName());
   }
}

Here each comparator compares a different attribute like roll number or name and can be used to sort the objects using Collections.sort() method.

Example

The following example shows the usage of Comparator to sort a list of students using roll number and their names respectively.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      Student s1 = new Student(1, "Zara");
      Student s2 = new Student(2, "Mahnaz");
      Student s3 = new Student(3, "Ayan");
      List<Student> list = new ArrayList<>(Arrays.asList(s2,s1,s3));
      System.out.println("List: " + list);
      Collections.sort(list, new RollNoComparator());
      System.out.println(list);
      Collections.sort(list, new NameComparator());
      System.out.println(list);
   }
}
class Student {
   private int rollNo;
   private String name;

   public Student(int rollNo, String name) {
      this.rollNo = rollNo;
      this.name = name;
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }

   @Override
   public String toString() {
      return "[" + this.rollNo + "," + this.name + "]";
   }
}
class RollNoComparator implements Comparator<Student>{
   @Override
   public int compare(Student s1, Student s2) {
      return s1.getRollNo() - s2.getRollNo();
   }
}
class NameComparator implements Comparator<Student>{
   @Override
   public int compare(Student s1, Student s2) {
      return s1.getName().compareTo(s2.getName());
   }
}

Output

This will produce the following result −

List: [[2,Mahnaz], [1,Zara], [3,Ayan]]
[[1,Zara], [2,Mahnaz], [3,Ayan]]
[[3,Ayan], [2,Mahnaz], [1,Zara]]

Advertisements