Java – JDK8 Comparator

Java 8 Comparator interface

  • Java 8 Comparator interface is a functional interface that contains only one abstract method.
  • It is providing many static and default methods to compare different types of object elements.
  • Now, we can use the Comparator interface as the assignment target for a lambda expression or method reference.

Sorting objects information using Student Age and Name:

Student.java:

class Student
{
            private int rollno;
            private String name;
            private int 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;
            }
}

Main.java:

import java.util.*;
public class Code
{
            public static void main(String args[])
            {
                        ArrayList<Student> al=new ArrayList<Student>();
                        int nums[] = {101, 102, 103, 104};
                        String names[] = {“Amar”, “Swathi”, “Sathya”, “Harin”};
                        int ages[] = {23, 30, 17, 25};
 
                        for(int i=0 ; i<nums.length ; i++)
                        {
                                    Student obj = new Student();
                                    obj.setRollno(nums[i]);
                                    obj.setName(names[i]);
                                    obj.setAge(ages[i]);
                                    al.add(obj);
                        }
 
                        Comparator<Student> cm1=Comparator.comparing(Student::getName);
                        Collections.sort(al,cm1);
                        System.out.println(“Sorting by Name”);
                        for(Student st: al)
                        {
                                    System.out.println(st.getRollno()+” , “+st.getName()+” , “+st.getAge());
                        }          
 
                        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.getRollno()+” , “+st.getName()+” , “+st.getAge());
                        }
            }
}
Scroll to Top