EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Comparator
Secondary Sidebar
Java 8 Tutorial
  • Java 8 basic
    • Java 8 forEach
    • Java 8 Documentation
    • Java 8 Method Reference
    • Java 8 List to Map
    • Java 8 Parallel Stream
    • Java 8 Functional Interface
    • Java 8 API
    • Java 8 Lambda
    • Java 8 Comparator
    • Java 8 Group By
    • Java 8 Predicate
    • Java 8 Default Methods
    • Java 8 Thread
    • Java 8 HashMap
    • Java 8 Read File
    • Java 8 OpenJDK
    • Java 8 Stream Filter
    • Java 8 Interface

Java 8 Comparator

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.

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.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - 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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*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?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more