Java 8 Stream - Sort List of Custom Objects in Ascending and Descending Order

In this source code example, we will learn how to sort a list of Person objects in ascending and descending order using Java 8 Stream API.

Java 8 Stream - Sort List of Custom Objects in Ascending and Descending Order

package com.java.tutorials.java8;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class JavaStreamExample {

    public static void main(String[] args) {
        List < Person > people = getPeople();

        // Sort in ascending order
        List < Person > sorted = people.stream()
            .sorted(Comparator.comparing(Person::getGender))
            .collect(Collectors.toList());
        sorted.forEach(System.out::println);

        System.out.println(" ************* ");
        // Sort in descending order
        List < Person > sortedDescending = people.stream()
            .sorted(Comparator.comparing(Person::getGender).reversed())
            .collect(Collectors.toList());
        sortedDescending.forEach(System.out::println);
    }

    private static List < Person > getPeople() {
        return List.of(new Person("Antonio", 20, Gender.MALE), new Person("Alina Smith", 33, Gender.FEMALE),
            new Person("Helen White", 57, Gender.FEMALE), new Person("Alex Boz", 14, Gender.MALE),
            new Person("Jamie Goa", 99, Gender.MALE), new Person("Anna Cook", 7, Gender.FEMALE),
            new Person("Zelda Brown", 120, Gender.FEMALE));
    }
}

enum Gender {
    MALE,
    FEMALE
}

class Person {

    private final String name;
    private final int age;
    private final Gender gender;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Gender getGender() {
        return gender;
    }

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender=" + gender + '}';
    }
}
Output:
Person{name='Antonio', age=20, gender=MALE}
Person{name='Alex Boz', age=14, gender=MALE}
Person{name='Jamie Goa', age=99, gender=MALE}
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Anna Cook', age=7, gender=FEMALE}
Person{name='Zelda Brown', age=120, gender=FEMALE}
 ************* 
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Anna Cook', age=7, gender=FEMALE}
Person{name='Zelda Brown', age=120, gender=FEMALE}
Person{name='Antonio', age=20, gender=MALE}
Person{name='Alex Boz', age=14, gender=MALE}
Person{name='Jamie Goa', age=99, gender=MALE}
Read more at https://www.javaguides.net/p/java-8-stream-api-tutorial.html.

Comments