×

java · level 3 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A points at a method that already exists.

Many lambdas only pass their value straight to one method: text -> text.toUpperCase(). A method reference says the same with less noise: String::toUpperCase. Read the double colon as "use this method here". System.out::println works the same way for printing.

Sorting is where they shine. sorts films by year. Add a tie-breaker with , which only matters when two years match, and flip an order with reversed().

Read a chain from left to right like a sentence: compare by year, then by title.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
    static class Film {
        private String title;
        private int year;
        Film(String title, int year) {
            this.title = title;
            this.year = year;
        }
        String getTitle() { return title; }
        int getYear() { return year; }
    }
    public static void main(String[] args) {
        List<Film> films = new ArrayList<>(List.of(
            new Film("Up", 2009), new Film("Coco", 2017),
            new Film("Cars", 2006), new Film("Avatar", 2009)));
        films.sort(Comparator.comparing(Film::getYear).thenComparing(Film::getTitle));
        films.forEach(film -> System.out.println(film.getYear() + " " + film.getTitle()));
        List.of("Roll", "the", "credits").forEach(System.out::println);
    }
}

Method references work best in chains like this, where a lambda would leave Java unsure of the type.