Java 8: Stream sorted

In this post, we are going to see how we can use Stream.sorted method to sort a collection with an example.

Consider that we have Person class contains “name” and “age” fields and want to sort the list of person objects by age and then by name.

Refer the below code to know how to do that.


import com.google.common.collect.Lists;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

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

public class CollectionMain {

    static class Person {
        String name;
        Integer age;

        Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE)
                .append("name", name)
                .append("age", age)
                .toString();
        }

        public String getName() {
            return name;
        }


        public Integer getAge() {
            return age;
        }

    }

    private static final Comparator PERSON_COMPARATOR = Comparator.comparing(Person::getAge).thenComparing(Person::getName);

    public static void main(String[] args) {
        List persons = Lists.newArrayList(new Person("John", 32),
            new Person("Tom", 33),
            new Person("Brad", 35),
            new Person("Varma", 38),
            new Person("Andy", 33));

        System.out.println(persons
            .stream()
            .filter(p -> p.age > 32)
            .sorted(PERSON_COMPARATOR)
            .collect(Collectors.toList()));

    }
}



[Andy,33, Tom,33, Brad,35, Varma,38]