Comparator In Java

Comparator In Java :

  • Use: Order the objects of user-defined classes.
  • Package: java.util package
  • Comparing two objects of two different classes.
  • Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
Comparator In Java

Syntax

public int compare(Object obj1, Object obj2):

import java.util.*;

class Student {

    int rollno;
    String name, address;

    // Constructor 
    public Student(int rollno, String name, String address) {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }

    @Override
    public String toString() {
        return this.rollno + " " + this.name
                + " " + this.address;
    }
}

class Sortbyroll implements Comparator<Student> {

    @Override
    public int compare(Student a, Student b) {
        return a.rollno - b.rollno;
    }
}

class Sortbyname implements Comparator<Student> {

    @Override
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name);
    }
}

class Main {
    public static void main(String[] args) {
        ArrayList<Student> ar = new ArrayList<Student>();
        ar.add(new Student(111, "kamlesh", "ahmedabad"));
        ar.add(new Student(131, "jay", "surat"));
        ar.add(new Student(121, "snehal", "mumbai"));

        System.out.println("Unsorted");
        for (int i = 0; i < ar.size(); i++) {
            System.out.println(ar.get(i));
        }

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

        System.out.println("\nSorted by rollno");
        for (int i = 0; i < ar.size(); i++) {
            System.out.println(ar.get(i));
        }

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

        System.out.println("\nSorted by name");
        for (int i = 0; i < ar.size(); i++) {
            System.out.println(ar.get(i));
        }
    }
}

output

Unsorted
111 kamlesh ahmedabad
131 jay surat
121 snehal mumbai

Sorted by rollno
111 kamlesh ahmedabad
121 snehal mumbai
131 jay surat

Sorted by name
131 jay surat
111 kamlesh ahmedabad
121 snehal mumbai

Sort collection by more than one field

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) {

        List<Student> al = new ArrayList<>();

        Student obj1 = new Student("Kamlesh", 27);
        Student obj2 = new Student("Vijay", 23);
        Student obj3 = new Student("Samir", 37);
        Student obj4 = new Student("Vijay", 22);
        Student obj5 = new Student("Jay", 29);
        Student obj6 = new Student("Mohit", 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

Before Sorting:
Customer{Name=Kamlesh, Age=27}
Customer{Name=Vijay, Age=23}
Customer{Name=Samir, Age=37}
Customer{Name=Vijay, Age=22}
Customer{Name=Jay, Age=29}
Customer{Name=Mohit, Age=22}

After Sorting:
Customer{Name=Jay, Age=29}
Customer{Name=Kamlesh, Age=27}
Customer{Name=Mohit, Age=22}
Customer{Name=Samir, Age=37}
Customer{Name=Vijay, Age=22}
Customer{Name=Vijay, Age=23}

Java 8 Comparator

Comparator<Student> cm1=Comparator.comparing(Student::getName);  
Collections.sort(al,cm1);  

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

class Student {

    int rollno;
    String name;
    int age;

    Student(int rollno, String name, int age) {
        this.rollno = rollno;
        this.name = name;
        this.age = age;
    }

    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;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

public class Main {
    public static void main(String args[]) {
        ArrayList<Student> al = new ArrayList<Student>();
        al.add(new Student(101, "Kamlesh", 23));
        al.add(new Student(106, "Hiren", 27));
        al.add(new Student(105, "Vijay", 21));
        Comparator<Student> cm1 = Comparator.comparing(Student::getName);
        //Comparator<Student> cm1 = Comparator.comparing(Student::getName,Comparator.nullsFirst(String::compareTo));  //null first
        //Comparator<Student> cm1 = Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo));  //null last
        Collections.sort(al, cm1);

        System.out.println("Sorting by Name");
        for (Student st : al) {
            System.out.println(st.rollno + " " + st.name + " " + st.age);
        }

        //Sorting age  
        Comparator<Student> cm2 = Comparator.comparing(Student::getAge);
        Collections.sort(al, cm2);
        System.out.println("Sorting by Age");

        for (Student st : al) {
            System.out.println(st.rollno + " " + st.name + " " + st.age);
        }
    }
}

output

Sorting by Name
106 Hiren 27
101 Kamlesh 23
105 Vijay 21

Sorting by Age
105 Vijay 21
101 Kamlesh 23
106 Hiren 27

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in