Java 8 Stream - Sort List of Objects by Multiple Fields

In this source code example, we will see how to sort a list of Person objects based on age and gender using java 8 Stream API.

Java 8 Stream - Sort List of Objects by Multiple Fields Example

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::getAge).thenComparing(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::getAge).thenComparing(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='Anna Cook', age=7, gender=FEMALE}
Person{name='Alex Boz', age=14, gender=MALE}
Person{name='Antonio', age=20, gender=MALE}
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Jamie Goa', age=99, gender=MALE}
Person{name='Zelda Brown', age=120, gender=FEMALE}
 ************* 
Person{name='Zelda Brown', age=120, gender=FEMALE}
Person{name='Jamie Goa', age=99, gender=MALE}
Person{name='Helen White', age=57, gender=FEMALE}
Person{name='Alina Smith', age=33, gender=FEMALE}
Person{name='Antonio', age=20, gender=MALE}
Person{name='Alex Boz', age=14, gender=MALE}
Person{name='Anna Cook', age=7, gender=FEMALE}
Read more at https://www.javaguides.net/p/java-8-stream-api-tutorial.html.

Comments