Sort User-Defined Objects in Ascending Order in Java

This is example demonstrates that we create a list of person objects and we compare each person's age by using compateTo() method of Comparable Interface. In short, we are sorting persons by age in ascending order.
Learn and master Java Collections Framework at Learn Java Collections Framework.

Sort User-Defined Objects in Ascending Order in Java

public class Person implements Comparable < Person > {

    private int id;

    private String name;

    private int age;

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

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String toString() {

    public int compareTo(Person otherPerson) {
        return (this.getAge() - otherPerson.getAge());
Note that Person class implements Comparable interface and provides compareTo() method implementation.

Here is code to test and sort person objects:
import java.util.ArrayList;

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

public class PersonSorterInASC {
    public static void main(String[] args) {


    private static void sortUserDefinedObjectsInAsc() {
        List < Person > persons = new ArrayList < Person > ();
        Person person1 = new Person(59, "John", 40);
        Person person12 = new Person(67, "Roger", 25);
        Person person13 = new Person(45, "Steven", 30);

        System.out.println("Before Sorting : " + persons);
        System.out.println("After Sorting : " + persons);


Before Sorting : [John, Roger, Steven]
After Sorting : [Roger, Steven, John]

Collections Examples

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course