1. Introduction

Java 8 introduced a new features and enhancements, particularly in the area of collections and stream processing. Among these, sorting custom objects has become more straightforward and expressive, thanks to lambda expressions and the Stream API. In this guide, we will explore how to sort custom objects in Java 8 using these powerful features.

2. Program Steps

1. Define a custom Person class with attributes like name and age.

2. Create a list of Person objects.

3. Sort the list by the name attribute in ascending order.

4. Sort the list by the age attribute in ascending order.

3. Code Program

import java.util.ArrayList;
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 + '}';
    }
}

public class SortCustomObjects {
    public static void main(String[] args) {
        // 2. Create a list of Person objects.
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // 3. Sort the list by the name attribute in ascending order.
        people.sort(Comparator.comparing(Person::getName));
        System.out.println("Sorted by name: " + people);

        // 4. Sort the list by the age attribute in ascending order.
        people.sort(Comparator.comparingInt(Person::getAge));
        System.out.println("Sorted by age: " + people);
    }
}

Output:

Sorted by name: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]
Sorted by age: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]

4. Step By Step Explanation

1. We define a Person class with attributes name and age. The class also includes getter methods and a toString() method for easy display.

2. We create a list of Person objects for sorting.

3. For sorting by name, we use the Comparator.comparing method combined with method references. The expression Person::getName is a method reference that points to the getName() method of the Person class. This provides a concise way to specify the sorting key.

4. For sorting by age, we use the Comparator.comparingInt method, which is a specialized version for integer keys. Again, we use a method reference Person::getAge to specify the sorting key.

With Java 8's lambda expressions and method references, sorting custom objects becomes a more streamlined and readable process.