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,doubleamount){List<Invoice>result=newArrayList<>();for(Invoiceinv:invoices){if(inv.getAmount()>amount){result.add(inv
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access