All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Sort List Of Objects In Java

Last Updated : Sep 1, 2023

Sort List Of Objects In Java

In this article we will show you the solution of sort list of objects in java, programmers frequently use sorting to arrange elements in a specific order for quick retrieval and analysis.

We'll discover various strategies for sorting a list of customised objects using both custom comparators and the standard library.

To sort the list of objects, we will use Java's built-in sorting features offered by the Collections class.

We will also use unique comparators to order items according to particular attributes.

To ensure a thorough knowledge of the sorting process, the tutorial will include code samples and step-by-step explanations.

Step By Step Guide On Sort List Of Objects In Java :-

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class People {
    private String name;
    private int age;
    public People(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 + "}";
    }
}
public class Sorting {
    public static void main(String[] args) {
        List<People> personList = new ArrayList<>();
        personList.add(new People("Anjali", 12));
        personList.add(new People("Vaishnavi", 13));
        personList.add(new People("Gauri", 16));
        Collections.sort(personList, new Comparator<People>() {
            @Override
            public int compare(People p1, People p2) {
                return p1.getName().compareTo(p2.getName());
            }
        });
        for (People person : personList) {
            System.out.println(person);
        }
    }
}
  1. Importing Necessary Classes: The java.util package is first used to import the necessary classes in the code. It covers List, Comparator, ArrayList, and Collections.
  2. Create the People Class: The code then creates a special class called People. The name and age private characteristics of this class each indicate a person's name and age, respectively. The class has getter methods to access these characteristics as well as a constructor to initialise them.
  3. Create a List of People Objects: The main function of the Sorting class is where a list called personList is created and used to store instances of the People class. With three different names and ages, three People objects are created and added to the list.
  4. Put Custom Sorting with Comparator into Practise: The code uses the Collections.sort() method, which accepts two arguments: the list to be sorted (personList), and a special Comparator implementation, to order the personList according to the name property. For ease of use, the Comparator is built in this case as an anonymous inner class.
  5. Replace compare Using the Comparator Method: The Collections.sort() method defines the ComparatorPeople> as an unnamed inner class. The compare method, which takes two People objects (p1 and p2) as input and outputs an integer, is overridden by this one.
  6. Logic Sorting in the Compare Method: p1.getName() in the comparison method.To compare the names of p1 and p2, use compareTo(p2.getName()). The String object that contains the names of each People object is called with the compareTo method. The comparison determines how the elements will be arranged after being compared.
  7. Sort the List: Following the definition of the custom comparator, the personList is sorted using the comparator by the Collections.sort() method, which reorders the components according to their names.
  8. The sorted list to print: The sorted personList is then iterated through using a for-each loop. Each People object's toString method, which was overridden in the People class to create a unique string representation, is used to print each one to the console.

Conclusion :-

Being able to sort a list of objects in Java is a fundamental activity, therefore knowing the various methods is crucial for any Java developer.

This article demonstrated how to use a custom comparator and the Collections.sort() method to order a list of custom objects.

We also learned how to use a custom comparator to sort the objects according to a particular attribute.

This information can be used in a variety of real-world situations where sorting is necessary, such as data organisation, report generation, or showing sorted information to end users.

I hope this article on sort list of objects in java helps you and the steps and method mentioned above are easy to follow and implement