Skip to main content

Command Palette

Search for a command to run...

Java Stream Operations Simplified - Part 3

Published
•2 min read•View as Markdown
Java Stream Operations Simplified - Part 3

In this post, we will look at some of the remaining terminal stream operations. Please refer to previous post on terminal stream operations.

IntermediateTerminal
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),
        );
  • anyMatch()

This operation will return true if any of the elements in the stream satisfy the predicate condition.

boolean hasAge3 = myPets
     .stream()
     .anyMatch(p -> p.age == 3);

// true
There exists atleast one pet which is 3 years old
  • allMatch()

This operation will return true if all the elements in the stream satisfy the predicate condition.

boolean hasAge3 = myPets
     .stream()
     .allMatch(p -> p.age == 3);

// false
Not all pets are 3 years old
  • noneMatch()

In contrast to allMatch, this operation will return true if all the elements in the stream do not satisfy the predicate condition.

boolean hasAge3 = myPets
     .stream()
     .noneMatch(p -> p.age == 20);

// true
No pets exists whose age is 20
  • findFirst()

This operation returns an optional describing the first element in the stream.

Optional<Pet> firstPetOptional = myPets
     .stream()
     .findFirst();

if (firstPetOptional.isPresent()) {
    System.out.println(firstPetOptional.get().getName());
}

// Molly
  • findAny()

This operation returns an optional containing any element in the stream.

Optional<Pet> firstPetOptional = myPets
     .stream()
     .findAny();

if (firstPetOptional.isPresent()) {
    System.out.println(firstPetOptional.get().getName());
}

// The result may be Molly , Jimmy, Rocky, Rabbu or Chirpie

Conclusion

In this post, we looked briefly upon some of the remaining terminal stream operations. For detailed information, please refer to the official Java Docs. You may also refer to previous posts Java Stream Operations Simplified - Part 1 and Java Stream Operations Simplified - Part 2