All TalkersCode Topics

Follow TalkersCode On Social Media

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

Java Sort Arraylist Of Objects By Field

Last Updated : Mar 11, 2024

Java Sort Arraylist Of Objects By Field

In this article we will show you the solution of java sort arraylist of objects by field, in general, we sort simple array lists with Collections.sort(). There are, however, two ways to sort an ArrayList if it's a custom object type - comparing and comparing.

Here we will see what happens if we don't implement any of these interfaces when sorting an ArrayList of Objects.

This is before we understand how to sort an ArrayList of ArrayLists using comparative and comparator.

It will be necessary to modify our class and define a default (or natural) sort order in order to accomplish this.

Sorting in descending order requires the use of two different methods.

A method reference is accepted by Comparator.Compare() as the basis for the comparison. As a result, User:getCreatedOn is passed in as a parameter for sorting by the createdOn field.

The original list would not be modified, but a newly sorted list would be returned instead. Java 8 Stream supports sort() method for accomplishing this.

The comparator can be passed into Collections.sort() rather than having to modify the class.

Our program compares the name and age fields one after another using the String class's compareTo() method and the Integer class's compare() method.

Many special cases are handled here, and a lot of typing is required. As a result, it is challenging to maintain and scale when we are comparing multiple fields at the same time.

Java provides overloaded sort() methods that can be used to sort different collections and use different comparators when arranging an array list.

The purpose of this tutorial is to teach you how to sort an ArrayList using a comparator in Java and how to order them based on the natural order they appear in.

Arrays can be sorted in decreasing order using the reverse comparator provided by the java.util.Collections class.

A reverse order() method can be used to retrieve this comparator.

A Java object stored in an ArrayList should implement a Comparable interface and implement the compareTo() method as per the natural order of its elements in order to sort it by its natural order.

If you want to sort an ArrayList in Custom order in Java, you must provide a Comparator along with the List.sort(List, Comparator).

The sorting of objects in an ArrayList will be defined through the compare() method.

Step By Step Guide On Java Sort Arraylist Of Objects By Field :-

import java.util.*;
public class TalkersCode {
    public static void main(String[] args) {
        Person person1 = new Person(1, "riyu", 20);
        Person person2 = new Person(2, "anshu", 21);
        Person person3 = new Person(3, "riyansh", 23);
        List<Person> persons = new ArrayList<>();
        persons.add(person1);
        persons.add(person2);
        persons.add(person3);
        System.out.println("Before: " + persons);
        persons.sort(new Comparator<Person>() {
            public int compare(Person p1, Person p2) {
                if (p1.getAge() == p2.getAge())
                    return 0;
                return p1.getAge() < p2.getAge() ? -1 : 1;
            }
        });
        System.out.println("After: " + persons);
    }
}
  1. Our first step is to import Java.util functions.
  2. Our next step is to create the class that will execute the program.
  3. Then the program is initialized by creating a public static void main.
  4. Creating a user list is the next step.
  5. A compare function is then used to sort the user list.
  6. Object 0 is returned then.
  7. After that, we close the program by calling system.out.printIn.

Conclusion :-

A Java object stored in an ArrayList should implement a Comparable interface and implement the compareTo() method as per the natural order of its elements in order to sort it by its natural order.

I hope this article on java sort arraylist of objects by field helps you and the steps and method mentioned above are easy to follow and implement.