X
    Categories: Java Core

Java Comparator Example

in this tutorial, we will discuss java comparator and its examples.

What is Java Comparator?

Java Comparator is an interface for arranging Java objects. Summoned by “java.util.comparator,” Java Comparator analyzes two Java protests in a “compare(Object 01, Object 02)” group.

Utilizing configurable strategies, Java Comparator can contrast objects with profit a number based for a positive, equivalent or negative correlation. Since it isn’t constrained to looking at numbers, this can permit Java Comparator to be set up to request records one after another in order or numerically. With java.io.Serializable, Java comparator can likewise be utilized to effectively arrange serialized information structures.

Java Comparator is like the Comparable interface yet is expected for characterizing exchange sort orders where Comparable sorts by regular requesting, for example, lexicographic arranging.



Syntax

public int compare(Object obj1, Object obj2):

How to use Java Comparator?

Both TreeSet and TreeMap store components in the arranged request. Be that as it may, it is the comparator that characterizes unequivocally what arranged request implies.

The Comparator interface characterizes two techniques: compare( ) and equals( ). The compare( ) strategy, appeared, looks at two components for request −

The compare Method

int compare(Object obj1, Object obj2)

obj1 and obj2 are questioned be looked at. This strategy returns zero if the articles are equivalent. It restores positive esteem if obj1 is more noteworthy than obj2. Something else, negative esteem is returned.

By abrogating compare( ), you can modify how protests are requested. For instance, to sort backward request, you can make a comparator that switches the result of an examination.

 

 

The Equals Method

The equals( ) strategy, appeared, tests whether an article squares with the conjuring comparator −

boolean equals(Object obj)

obj is the article to be tried for fairness. The strategy returns genuine if obj and the summoning object are both Comparator articles and utilize a similar requesting. Else, it returns false.

Abrogating equals( ) is superfluous, and most straightforward comparators won’t do as such.

 

Java Comparator Example

import java.util.*;

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

public class Example {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));
      Collections.sort(list);   // Sorts the array list

      for(Dog a: list)   // printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");
      
      for(Dog a: list)   // printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+ a.getDogAge() + ", ");
   }
}

 

OUTPUT:
Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy  : 1, Lacy  : 2, Shaggy  : 3, Tommy  : 4, Roger  : 10,

 

Working Examples of Java comparator.

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Comparator; 
  
class Student { 
  
    // instance member variables 
    String Name; 
    int Age; 
  
    // parameterized constructor 
    public Student(String Name, Integer Age) { 
        this.Name = Name; 
        this.Age = Age; 
    } 
  
    public String getName() { 
        return Name; 
    } 
  
    public void setName(String Name) { 
        this.Name = Name; 
    } 
  
    public Integer getAge() { 
        return Age; 
    } 
  
    public void setAge(Integer Age) { 
        this.Age = Age; 
    } 
  
    // overriding toString() method 
    @Override
    public String toString() { 
        return "Customer{" + "Name=" + Name + ", Age=" + Age + '}'; 
    } 
  
    static class CustomerSortingComparator implements Comparator<Student> { 
  
        @Override
        public int compare(Student customer1, Student customer2) { 
  
            // for comparison 
            int NameCompare = customer1.getName().compareTo(customer2.getName()); 
            int AgeCompare = customer1.getAge().compareTo(customer2.getAge()); 
  
            // 2-level comparison using if-else block 
            if (NameCompare == 0) { 
                return ((AgeCompare == 0) ? NameCompare : AgeCompare); 
            } else { 
                return NameCompare; 
            } 
        } 
    } 
  
    public static void main(String[] args) { 
  
        // create ArrayList to store Student 
        List<Student> al = new ArrayList<>(); 
  
        // create customer objects using constructor initialization 
        Student obj1 = new Student("Ajay", 27); 
        Student obj2 = new Student("Sneha", 23); 
        Student obj3 = new Student("Simran", 37); 
        Student obj4 = new Student("Ajay", 22); 
        Student obj5 = new Student("Ajay", 29); 
        Student obj6 = new Student("Sneha", 22); 
  
        // add customer objects to ArrayList 
        al.add(obj1); 
        al.add(obj2); 
        al.add(obj3); 
        al.add(obj4); 
        al.add(obj5); 
        al.add(obj6); 
  
        // before Sorting arraylist: iterate using Iterator 
        Iterator<Student> custIterator = al.iterator(); 
  
        System.out.println("Before Sorting:\n"); 
        while (custIterator.hasNext()) { 
            System.out.println(custIterator.next()); 
        } 
  
        // sorting using Collections.sort(al, comparator); 
        Collections.sort(al, new CustomerSortingComparator()); 
  
        // after Sorting arraylist: iterate using enhanced for-loop 
        System.out.println("\n\nAfter Sorting:\n"); 
        for (Student customer : al) { 
            System.out.println(customer); 
        } 
    } 
}

 

 

Output:

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Sorted by name
131 aaaa nyc
111 bbbb london
121 cccc jaipu

 

 

0 0 votes
Article Rating
asimassu101:
Related Post