Open In App

How to Compare Objects by Multiple Fields in Java?

Last Updated : 28 Feb, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

In Java, A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. In this article, we will learn how to compare objects by multiple fields.

Compare Objects by Multiple Fields

To compare objects by multiple fields in Java using a Custom Comparator, you can follow this approach, Suppose you have a class MyClass with fields field1, field2, and field3. You want to compare objects of this class first by field1, then by field2, and finally by field3.

Let's consider a scenario where you have a `Person` class with fields `name`, `age`, and `city`. We want to compare `Person` objects first by name, then by age, and finally by city.

Person Class:

public class Person {
    private String name;
    private int age;
    private String city;
    // Constructors, getters, and setters
}

Java Program to Compare Objects by Multiple Fields

Below is the Program to Compare Objects by Multiple Fields:


Output
Alice, 30, London
Bob, 25, Paris
John, 25, New York

Expalnation of the above Program:

The above program demonstrates how to define a custom comparator to compare objects by multiple fields and use it to sort a list of objects based on this comparison logic. It's a common pattern used when you need to sort objects by multiple criteria simultaneously.


Next Article
Practice Tags :

Similar Reads