EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Comparator
 

Java 8 Comparator

Updated February 10, 2023

Introduction to Java 8 Comparator

The Java 8 comparator is used to order the objects of the class that was defined. It can be found in java.util package and includes two methods: public int compare and public Boolean equals. It provides multiple sequences, allowing us to sort the elements based on data members. A comparator is used at times we want to sort collection objects.

 

 

It is used to sort the collection objects which we compare with each other. This comparison, we are doing is by using a comparable interface, but we restrict the objects in a particular way. In Java, we use the comparator to sort the collection according to the criteria. The method is introduced in java version 8.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

The Java 8 comparator object returns the comparator object that used the specified field as the sort key. The comparator interface is a functional interface that was used in java 8, and it was implemented in compare method. The method is implemented by using comparing method and a specified key.

Java 8 Comparator

Key Takeaways

  • The java 8 comparator method is a collection of class that was used in sorting the elements as per the list by using a specified comparator.
  • In java 8 comparator sort method calls the compare method for the classes to sort the object which we have defined.

How to Use Java 8 Comparator?

To use it, we need to define the java class first; after defining the java class then, we are defining the comparator class then we are defining another comparator class after defining the comparator class then, we are defining the simple java class, which contains the main method.

The below steps show how we can use the comparator as follows:

1. In the first step, we define the simple java class, which contains the details of the student class as follows.

Code:

package comparator;
class Stud {
int stud_no;
String stud_name;
int stud_age;
Stud(int stud_no, String stud_name, int stud_age)
{
this.stud_no = stud_no;
this.stud_name = stud_name;
this.stud_age = stud_age;
}
}

Java 8 Comparator - Student class

2. After defining the simple java class, now in this step, we are defining the first comparator class as follows.

Code:

package comparator;
import java.util.*;
class SAge_comparator implements Comparator<Stud>
{
public int compare (Stud s1, Stud s2)
{
if(s1.stud_age == s2.stud_age)
return 0;
else if(s1.stud_age > s2.stud_age)
return 1;
else
return -1;
}
}

Java 8 Comparator Class

3. After defining the first comparator class now, in this step, we are defining the second comparator class as follows.

Code:

package comparator;
import java.util.*;
class SName_comparator implements Comparator<Stud>
{
public int compare(Stud s1,Stud s2)
{
return s1.stud_name.compareTo(s2.stud_name);
}
}

Java 8 Second Comparator

4. After defining the comparator class, now in this step, we are defining a simple class that contains the main method.

Code:

package comparator;
import java.util.*;
import java.io.*;
class SimpleStud {
public static void main(String[] args) {
ArrayList<Stud> al=new ArrayList<Stud>();
al.add(new Stud (101,"ABC",23));
al.add(new Stud (102,"PQR",27));
al.add(new Stud (103,"XYZ",21));
System.out.println("Sorting by stud_name");
Collections.sort(al, new SName_comparator());
for(Stud st: al){
System.out.println(st.stud_no+" "+st.stud_name+" "+st.stud_age);
}
System.out.println("Sorting by stud_age");
Collections.sort(al,new SAge_comparator());
for(Stud st: al){
System.out.println(st.stud_no+" "+st.stud_name+" "+st.stud_age);
}
}
}

Java 8 Comparator - Simple Class

5. After defining the simple java class now in this step, we are running our application as follows:

Java 8 Comparator Application

Java 8 Lambda Comparator

The lambda is an anonymous method that was not executing its own in java. Instead of executing its own code, we are implementing the method that makes use of the functional interface. We are using lambda by using a comparator and functional interface. To sort the collection objects, the comparator interface is used.

In the below example, we are defining the simple java class, which defined the variable of student class as follows.

Code:

package comparator2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class student {
int stud_id;
String stud_name;
public student(int stud_id, String stud_name) {
super();
this.stud_id = stud_id;
this.stud_name = stud_name;
}
}

Output:

Simple Java 8 Comparator Class

After defining the simple class now in this step, we are defining the lambda in the comparator as follows.

Code:

package comparator2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Lambda {
public static void main(String[] args) {
List<student> list = new ArrayList<student>();
list.add (new student(125, "ABC"));
list.add (new student(145, "PQR"));
list.add (new student(125, "XYZ"));
System.out.println("Sorting the stud name");
Collections.sort (list, (p1, p2) -> {
return p1.stud_name.compareTo(p2.stud_name);
});
for (student s : list) {
System.out.println(s.stud_id + " " + s.stud_name);
}
}
}

Output:

defining the lambda

Lambda expressions

Method

Below are the two methods mentioned:

  • public int compare(object obj1, object obj2): This method compares the first object by using the second object. We are comparing two objects using this method.
  • public boolean equals(object obj): This method is used to compare the current object by using the specified object.

In the below example, we are using the first method as follows:

Code:

package comparator;
import java.util.*;
class comp implements Comparator<Stud> {
public int compare(Stud s1, Stud s2) {
if(s1.stud_age==s2.stud_age)
return 0;
else if(s1.stud_age>s2.stud_age)
return 1;
else
return -1;
}
}

Output:

Java 8 Comparator - Object method

Examples

In the below example, we are creating emp class as follows.

Code:

package comparator3;
class emp{
int emp_no;
String emp_name;
int emp_age;
emp(int emp_no, String emp_name, int emp_age){
this.emp_no = emp_no;
this.emp_name = emp_name;
this.emp_age = emp_age;
}
}

Output:

creating emp class

After creating the simple java class now in this step, we are defining the first comparator class as follows.

Code:

package comparator3;
import java.util.Comparator;
class EAge_comparator implements Comparator<emp>
{
public int compare(emp e1, emp e2)
{
if(e1.emp_age==e2.emp_age)
return 0;
else if(e1.emp_age > e2.emp_age)
return 1;
else
return -1;
}
}

Output:

First Java 8 Comparator

After creating the first comparator class, now in this step, we are creating the second comparator class as follows.

Code:

package comparator3;
import java.util.Comparator;
class EName_comparator implements Comparator<emp>
{
public int compare(emp e1,emp e2)
{
return e1.emp_name.compareTo(e2.emp_name);
}
}

Output:

Second Java 8 Comparator

After creating the comparator classes now in this step, we are creating the java class, which contains the main method as follows.

Code:

package comparator3;
import java.util.*;
import java.io.*;
class EmapMain {
public static void main(String[] args) {
ArrayList<emp> al=new ArrayList<emp>();
al.add(new emp (1211,"ABC",29));
al.add(new emp (1312,"PQR",36));
al.add(new emp (1413,"XYZ",41));
System.out.println("Sorting by emp_name");
Collections.sort(al,new EName_comparator());
For (emp st: al) {
System.out.println(st.emp_no+" "+st.emp_name+" "+st.emp_age);
}
System.out.println("Sorting by emp_age");
Collections.sort(al, new EAge_comparator());
for (emp st: al) {
System.out.println(st.emp_no+" "+st.emp_name+" "+st.emp_age);
}
}
}

Output:

Main method

class which contains the main method

FAQs

Given below are the FAQs mentioned:

Q1. What is the use of java 8 comparator?

Answer: It is used to order the object into the user-defined class. The interface is found in java.util package.

Q2. Which methods we are using in the java 8 comparator?

Answer: We are using two methods i.e. public int compare and public boolean equals.

Q3. What is the use of the public int compare method in java 8 comparator?

Answer: The public int compare method is used to compare two objects as per the integer objects. After comparing the objects, it will sort the results.

Conclusion

The comparator interface is a functional interface that was used in java 8, and it was implemented in compare method. It is used to order the objects of the class that was defined. It is found in java.util package, and it will contain the two methods i.e. public int compare and public boolean equals.

Recommended Articles

This is a guide to Java 8 Comparator. Here we discuss the introduction, how to use java 8 comparator, methods, and examples. You may also have a look at the following articles to learn more –

  1. Text File in Java
  2. Java 8 forEach
  3. Java for Automation Testing
  4. Java SFTP

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW