Created: 2023-09-06 14:22
Status: #concept
Subject: Programming
Tags: Java java.util Java Package java.util.Comparable java.util.Stream

java.util.Comparator

A library containing static methods for building Comparable functions for sorting Java Streams.

  • the Comparator.comparing(lambda) will return a Comparator<T> which we can chain with .thenComparing(lambda) as many times as we want.
  • .reversed() is a terminating method to reverse the ordering based on the chained Comparator<T> functions.

List<Film> films = new ArrayList<>();
films.add(new Film("A", 2000));
films.add(new Film("B", 1999));
films.add(new Film("C", 2001));
films.add(new Film("D", 2000));

for (Film e: films) {
    System.out.println(e);
}

Comparator<Film> comparator = Comparator
              .comparinggetReleaseYear
              .thenComparinggetName;

Collections.sort(films, comparator);

for (Film e: films) {
    System.out.println(e);
}

References