Chapter 4 · Robust, modern Java

Lambdas and streams

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

Code you can pass

Some methods need a small piece of code from you: "which of two names comes first?", "which items go?".

In this lesson you will:

  • pass such code to a method as a lambda,
  • sort, filter and print a list with lambdas,
  • filter, change and add up a list in one chain: a stream.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ByLength {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of(
                "Margaret", "Ada", "Grace", "Alan", "Bo"));
        Comparator<String> byLength =
                (a, b) -> a.length() - b.length();
        names.sort(byLength);
        System.out.println(names);
    }
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ByLength {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of(
                "Margaret", "Ada", "Grace", "Alan", "Bo"));
        Comparator<String> byLength =
                (a, b) -> a.length() - b.length();
        names.sort(byLength);
        System.out.println(names);
    }
}
import java.util.ArrayList;
import java.util.List;

public class Names {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of(
                "Margaret", "Ada", "Grace", "Alan", "Bo"));
        names.sort((a, b) -> a.length() - b.length());
        System.out.println(names);
        names.removeIf(n -> n.length() < 4);
        names.forEach(n -> System.out.println("Hello, " + n));
    }
}
import java.util.ArrayList;
import java.util.List;

public class Scores {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>(
                List.of(72, 45, 90, 38, 66));
        // sort from highest to lowest

        // remove the scores under 50

        // print each score on a line of its own
    }
}
import java.util.List;

public class Words {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "kiwi", "banana",
                "fig", "cherry");
        System.out.println(words.stream()
                .filter(w -> w.length() > 4)
                .map(w -> w.toUpperCase())
                .toList());
    }
}
import java.util.List;
import java.util.stream.Collectors;

public class Fruit {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "kiwi", "banana",
                "fig", "cherry");

        List<String> longOnes = words.stream()
                .filter(w -> w.length() > 4)
                .map(w -> w.toUpperCase())
                .toList();
        System.out.println(longOnes);

        int letters = words.stream()
                .mapToInt(w -> w.length())
                .sum();
        System.out.println("Letters: " + letters);

        String shortOnes = words.stream()
                .filter(w -> w.length() <= 4)
                .collect(Collectors.joining(", "));
        System.out.println("Short: " + shortOnes);
    }
}
import java.util.List;

public class Shop {
    static List<String> cheap(List<Item> items, int limit) {
        return List.of();
    }

    static int total(List<Item> items) {
        return 0;
    }

    public static void main(String[] args) {
        List<Item> items = List.of(new Item("bread", 3),
                new Item("cheese", 8), new Item("apples", 4),
                new Item("coffee", 12), new Item("milk", 2));
        System.out.println(cheap(items, 5));
        System.out.println("Total: " + total(items));
    }
}
import java.util.List;
import java.util.stream.Collectors;

public class Initials {
    static String initials(List<String> names) {
        return "";
    }

    public static void main(String[] args) {
        List<String> a = List.of("Ada", "Grace", "Linus");
        List<String> b = List.of("Margaret", "Alan");
        System.out.println(initials(a));
        System.out.println(initials(b));
    }
}
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Report {
    // sorts the students, highest score first
    static void sortByScore(List<Student> students) {
    }

    // names of the students who scored 60 or more
    static List<String> passed(List<Student> students) {
        return List.of();
    }

    // every score added up
    static int total(List<Student> students) {
        return 0;
    }

    // every name, separated by ", "
    static String names(List<Student> students) {
        return "";
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(List.of(
                new Student("Grace", 58),
                new Student("Ada", 92),
                new Student("Alan", 40),
                new Student("Linus", 75)));
        sortByScore(students);
        students.forEach(s ->
                System.out.println(s.name() + " " + s.score()));
        System.out.println("Passed: " + passed(students));
        System.out.println("Total: " + total(students));
        System.out.println("Everyone: " + names(students));
    }
}
import java.util.List;

public class Top {
    public static void main(String[] args) {
        List<Student> students = List.of(
                new Student("Grace", 58),
                new Student("Ada", 92),
                new Student("Alan", 40),
                new Student("Linus", 75),
                new Student("Joan", 81));
        List<String> top = students.stream()
                // keep the three best, highest first
                .map(s -> s.name())
                .toList();
        System.out.println(top);
    }
}
Terminal
Step 1 of 10Sort by length

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)