Java Comparator Custom Object Sorting Example

In this tutorial, we will explore how to use the Comparator interface to sort custom objects in Java. We will create a custom object, implement a comparator to sort these objects based on specific attributes and use the latest Java version to ensure modern practices and features.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Step-by-Step Guide
    1. Create a Custom Object
    2. Implement a Comparator for Custom Object
    3. Sort the List of Custom Objects
    4. Print the Sorted List
  4. Complete Code Example
  5. Conclusion

Introduction

Sorting custom objects in Java often requires custom sorting logic based on specific attributes. The Comparator interface allows us to define this custom logic. In this tutorial, we will demonstrate how to sort a list of custom objects by their attributes using the Comparator interface.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed (latest version preferred)
  • An Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse

Step-by-Step Guide

Step 1: Create a Custom Object

First, let's create a custom object named Person with attributes name and age.

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

Step 2: Implement a Comparator for Custom Object

Next, we will implement a custom comparator to sort the Person objects first by name in a case-insensitive manner and then by age.

import java.util.Comparator;

public class PersonComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        int nameComparison = p1.getName().compareToIgnoreCase(p2.getName());
        if (nameComparison != 0) {
            return nameComparison;
        } else {
            return Integer.compare(p1.getAge(), p2.getAge());
        }
    }
}

Step 3: Sort the List of Custom Objects

Now, we will create a list of Person objects and sort it using our custom comparator.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CustomObjectSortingExample {
    public static void main(String[] args) {
        // Create a list of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("bob", 22));
        people.add(new Person("john", 20));
        people.add(new Person("Alice", 25));

        // Sort the list using the custom comparator
        Collections.sort(people, new PersonComparator());
    }
}

Step 4: Print the Sorted List

Finally, we will print the sorted list to verify that the Person objects are sorted first by name and then by age.

public class CustomObjectSortingExample {
    public static void main(String[] args) {
        // Create a list of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("bob", 22));
        people.add(new Person("john", 20));
        people.add(new Person("Alice", 25));

        // Sort the list using the custom comparator
        Collections.sort(people, new PersonComparator());

        // Print the sorted list
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

Complete Code Example

Here's the complete code example for sorting custom objects using Comparator:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

class PersonComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        int nameComparison = p1.getName().compareToIgnoreCase(p2.getName());
        if (nameComparison != 0) {
            return nameComparison;
        } else {
            return Integer.compare(p1.getAge(), p2.getAge());
        }
    }
}

public class CustomObjectSortingExample {
    public static void main(String[] args) {
        // Create a list of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("bob", 22));
        people.add(new Person("john", 20));
        people.add(new Person("Alice", 25));

        // Sort the list using the custom comparator
        Collections.sort(people, new PersonComparator());

        // Print the sorted list
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

Conclusion

In this tutorial, we demonstrated how to sort a list of custom objects using Java's Comparator interface. By creating a custom comparator, we were able to define sorting logic based on specific attributes of the Person objects. This approach provides flexibility and efficiency in sorting custom objects.

Comments