Java from Basics to Mastery — Part 6
Creating data flows with Lambda, Stream, and Optional
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
Code that selects, converts, and combines values that meet conditions in a collection appears frequently. Lambda and Stream express the stages through which data goes through a flow of operations.
Lambda
Predicate<Monster> isAlive = monster -> monster.getHealth() > 0;
Function<Monster, String> getName = Monster::getName;
Lambdas allow actions to be passed as values. Method references are concise when using an existing method in the same function form.
Stream pipeline
List<String> targetNames = monsters.stream()
.filter(Monster::isAlive)
.sorted(Comparator.comparingInt(Monster::getHealth))
.limit(3)
.map(Monster::getName)
.toList();
The flow is to sort living monsters in order of physical strength and get three names. Intermediate operations are usually executed when the final operation is called.
Once a stream is consumed, the same stream cannot be used again. You must repeatedly query the original collection or store the results as a list.
Optional
Optional<Item> item = repository.find(10);
String name = item
.map(Item::getName)
.orElse("Unknown");
Optional indicates to the return type that the value may or may not be present. If you call get() directly, none processing will be lost again, so use operations such as orElse, map, and ifPresent.
Optional is often used to express the absence of a return value rather than using it for all fields and parameters.
Performance and readability
Streams are not always faster than loops and can result in small operation objects and result lists. It is better to start with an easy-to-read flow and then change only the repetitive paths that cause problems in actual measurements to simple loops.
The purpose of lambdas and streams is not to make the code the shortest possible. The goal is to make data processing steps such as filtering, transformation, and sorting readable without side effects.