Hi All,

Greeting of the day!

Today we will explore terminal operations of stream in java 8 which are most frequently used. So let's start.

What are terminal operations - Terminal operations are stream operations which return the void or non-stream results instead of another stream hence called terminal operations.

Terminal operations are applied after intermediate operations.

Below are important terminal operations

  • Stream.count()
  • Stream.min()
  • Stream.max()
  • Stream.anyMatch()
  • Stream.allMatch()
  • Stream.collect()
  • Stream.forEach()
We will take consider below Book class and the list of books to apply all terminal operations.

Book.java



So let's explore the above operations in detail.

Stream.count() returns no of the element in stream, in the below example we will use an intermediate operation filter on the input stream, and then we will use the terminal operation to count the element present after filtering.

long count();


O/P Total available books of spring  2

Stream.min() - is a terminal operation used to find a minimum element from the input stream.
Optional<T> min(Comparator<? super T> comparator);

As you can see we need to pass a comparator for comparing all elements of the stream. In the below example, we are finding the cheapest book from all books.


O/P Book - [bookId=1, bookName=Introduction to java, bookPrice=575]

Stream.max() - is a terminal operation used to find the maximum element from the input stream.

Optional<T> max(Comparator<? super T> comparator);


O/P - Book [bookId=1, bookName=REST With Spring, bookPrice=800]

Stream.anyMatch()- is a terminal operation returning a boolean value, i.e true if the stream contains any element that matches the given predicate.

boolean anyMatch(Predicate<? super T> predicate); 

Example

O/P -  List contains Rest API Book::true

Stream.allMatch() - is a terminal operation that returns true when all elements of the stream match the given predicate.

boolean allMatch(Predicate<? super T> predicate);


O/P - Price of all books is greater than 600 false

Stream.collect() - is used to collect elements back after applying other intermediate operations.

Example

O/P [Book [bookId=1, bookName=Introduction to java, bookPrice=575], Book [bookId=2, bookName=REST With Spring, bookPrice=800]]

Stream.forEach() - is used to iterate elements of the stream and perform any operation on each element.


O/P

INTRODUCTION TO JAVA
REST WITH SPRING
SPRING SECURITY

So we have covered most of the terminal operations of the stream, let me know if you have any questions.

You can refer below useful post






For spring visit Spring Tutorial


Thanks
Happy Learning!