What is Comparator Interface and Comparator Examples

Published May 19, 2022

Generally, it is not possible to compare the user-defined class objects in Java. To make the class comparable, we need to implement the comparable interfaces.

The comparator interface is contained in the Java.util.package, and it contains the two methods compare (Object obj1, Object obj2) and equals(Object element). The compare (Object obj1, Object obj2) is used to compare the first object with another, while the equals(Object element) is used to compare the current object with the object specified.

 

Example

import java.util.*;

class PLanguage {

    int langno;

    String langname;

    String langcode;

    public PLanguage (int langno, String langname, String langcode)

    {

        this.langno = langno;

        this.langname = langname;

        this.langcode = langcode;

    }

 

    public String toString()

    {

        return this.langno + " " + this.langname + " "

            + this.langcode;

    }

}

 

class Sortbyroll implements Comparator<PLanguage> {

    public int compare(PLanguage a, PLanguage b)

    {

        return a.langno - b.langno;

    }

}

class Sortbyname implements Comparator<PLanguage> {

    public int compare(PLanguage a, PLanguage b)

    {

        return a.langname.compareTo(b.langname);

    }

}

public class Comparator_Interface_Example {

 

            public static void main(String[] args) {

       ArrayList<PLanguage> our_array_List = new ArrayList<PLanguage>();

        our_array_List.add(new PLanguage(100, "Java", "Android"));

        our_array_List.add(new PLanguage(20, "Kotlin", "Android"));

        our_array_List.add(new PLanguage(40, "Laravel", "Web"));

        our_array_List.add(new PLanguage(56, "Bootsrap", "Web"));

        System.out.println("Unsorted");

        for (int i = 0; i < our_array_List.size(); i++)

            System.out.println(our_array_List.get(i));

        Collections.sort(our_array_List, new Sortbyroll());

        System.out.println("\nSorted by Languag no");

        for (int i = 0; i < our_array_List.size(); i++)

            System.out.println(our_array_List.get(i));

        Collections.sort(our_array_List, new Sortbyname());

        System.out.println("\nSorted by Language name");

        for (int i = 0; i < our_array_List.size(); i++)

            System.out.println(our_array_List.get(i));

 

            }

 

}

 

Output

Unsorted

100 Java Android

20 Kotlin Android

40 Laravel Web

56 Bootsrap Web

 

Sorted by rollno

20 Kotlin Android

40 Laravel Web

56 Bootsrap Web

100 Java Android

 

Sorted by name

56 Bootsrap Web

100 Java Android

20 Kotlin Android

40 Laravel Web

 

Keywords: Comparator interfaces, How to Sort Objects with Comparator

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

103 Views