How to Compare Objects by Multiple Fields in Java?
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:
Java
// Java Program to Compare Objects by Multiple Fields import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; // Driver Class public class Person { private String name; private int age; private String city; // Constructor public Person(String name, int age, String city) { this .name = name; this .age = age; this .city = city; } // Getter methods public String getName() { return name; } public int getAge() { return age; } public String getCity() { return city; } // Nested Comparator class for comparing Person objects public static class PersonComparator implements Comparator<Person> { @Override public int compare(Person p1, Person p2) { // Compare by name int nameComparison = p1.getName().compareTo(p2.getName()); if (nameComparison != 0 ) { return nameComparison; } // If names are the same, compare by age int ageComparison = Integer.compare(p1.getAge(), p2.getAge()); if (ageComparison != 0 ) { return ageComparison; } // If names and ages are the same, compare by // City return p1.getCity().compareTo(p2.getCity()); } } // Main Method for Testing public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add( new Person( "John" , 25 , "New York" )); people.add( new Person( "Alice" , 30 , "London" )); people.add( new Person( "Bob" , 25 , "Paris" )); // Sorting the List Using the Custom Comparator Collections.sort(people, new PersonComparator()); // Displaying the Sorted List for (Person person : people) { System.out.println(person.getName() + ", " + person.getAge() + ", " + person.getCity()); } } } |
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.