Chapter 2. Adopting Lambda Expressions

In this chapter, you’ll learn how to adopt lambda expressions, the flagship feature of Java 8. First, you’ll learn about a pattern called behavior parameterization, which lets you write code that can cope with requirement changes. Then, you’ll see how lambda expressions let you use this pattern in a more concise way than what was possible before Java 8. Next, you’ll learn precisely where and how to use lambda expressions. You’ll also learn about method references, another Java 8 feature that lets you write code that is more succinct and descriptive. You’ll then bring all this new knowledge together into a practical refactoring example. Finally, you’ll also learn how to test using lambda expressions and method references.

Why Lambda Expressions?

The motivation for introducing lambda expressions into Java is related to a pattern called behavior parameterization. This pattern lets you cope with requirement changes by letting you write more flexible code. Prior to Java 8, this pattern was very verbose. Lambda expressions fix that by letting you utilize the behavior parameterization pattern in a concise way. Here’s an example: say you need to find invoices greater than a certain amount. You could create a method findInvoicesGreaterThanAmount:

List<Invoice> findInvoicesGreaterThanAmount(List<Invoice> invoices, double amount) {
    List<Invoice> result = new ArrayList<>();
    for(Invoice inv: invoices) {
        if(inv.getAmount() > amount) {
            result.add(inv

Get Introducing Java 8 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.