Java Stream Operations Simplified - Part 2

In this post, we will look at some of the terminal stream operations. A terminal operation is applied to the end of intermediate operations. They help to return a result from a stream.
| Intermediate | Terminal |
| filter() | count() |
| map() | forEach() |
| flatMap() | collect() |
| sorted() | max() |
| distinct() | min() |
| peek() | reduce() |
| skip() | anyMatch() |
| limit() | allMatch() |
| noneMatch() | |
| findFirst() | |
| findAny() |
Terminal Operations
Taking our previous example of list of pets and adding more pets.
List<Pet> myPets =
List.of(
new Pet("Molly", Type.CAT, 2),
new Pet("Jimmy", Type.DOG, 3),
new Pet("Rocky", Type.DOG, 3),
new Pet("Chirpie", Type.BIRD, 5),
new Pet("Rabbu", Type.RABBIT, 1),
);
count()
This operation will return the number of elements in the stream.
myPets
.stream()
.filter(p -> p.type.equals(Type.DOG))
.count();
// 2
forEach()
This method is used to iterate through the elements of the stream. It does not return any value.
myPets
.stream()
.forEach(p -> System.out.println(p.getName()));
// Molly
// Jimmy
// Rocky
// Chirpie
// Rabbu
collect()
This method is used to iterate through the elements of the stream and then collect them into a collection or some kind of object.
List<Pet> seniorPets = myPets
.stream()
.filter(p -> p.getAge > 2)
.collect(Collectors.toList());
// This will create a new collection where the ages of pets are greater than 2
max()
This method is used to return the maximum element in the stream according to the specified comparator.
Optional<Pet> optionalPet = myPets
.stream()
.max((p1, p2) -> p1.getAge() - p2.getAge());
// max() returns an optional
if (optionalPet.isPresent()) {
System.out.print(optionalPet.get().getName());
}
// This will return a pet which is the oldest
min()
This operation is the opposite of max(). This method is used to return the minimum element in the stream according to the specified comparator.
Optional<Pet> optionalPet = myPets
.stream()
.min((p1, p2) -> p1.getAge() - p2.getAge());
// min() returns an optional
if (optionalPet.isPresent()) {
System.out.print(optionalPet.get().getName());
}
// This will return the youngest pet
// Rabbu
reduce()
This operation is used to reduce all elements in the stream to a single element.
Optional<String> names = myPets
.stream()
.reduce((p1, p2) -> p1.getName()+" , "+p2.getName());
if (names.isPresent()) {
System.out.print(optionalPet.get());
}
// Molly, Jimmy, Rocky, Chirpie, Rabbu
Conclusion
In this post, we looked briefly upon some terminal stream operations. For detailed information, please refer to the official Java Docs.

