1.4-Software-Development-Principles

Week 2 - Lambda expressions and streams

Summary

Java 8 in Action - Lambdas, Streams, and functional-style programming

Java 8 allows new syntax that make common manipulations of lists much more concise. This requires us to get used to new notations, but is makes the intent of the code easily understandable:

inventory.sort(comparing(Apple::getWeight));

Without understanding how this works in detail you would probably guess that the inventory list is now sorted based on the weight of the containing apples. (And you would be right.)

Additionally, lambda expressions allow you to write code that resembles the way of thinking for (SQL) queries. Many list manipulations are similar to those kinds of operations. Why would you write code to do all these common things.

Finally, through the use of lambda expressions we can unittest pieces of code that are intended to fail with an exception. We want to actively trigger that exception, so that we can confirm that the correct exception was thrown with the expected content.

Theory

Video

Passing behaviour

Bad weather tests