$show=/label

Java 8 - 14 Stream Terminal Operations With Examples

SHARE:

Java 8 Stream API code with practical working examples for all terminal operations.

1. Overview


In this tutorial, We'll learn What are Terminal Operations in Java 8. List all Java 8 Stream Terminal Operations with Examples.
  • Java-8 Stream terminal operations produce a non-stream, result such as primitive value, a collection or no value at all.
  • Terminal operations are typically preceded by intermediate operations that return another Stream which allows operations to be connected in a form of a query. OR
  • Terminal operations can be performed on Java Stream directly.

Java 8 - 14 Stream Terminal Operations With Examples


Whereas Stream Intermediate operations produce a stream as a result.




2. List Terminal Operations


Here is the list of all Stream terminal operations:

toArray()
collect()
count()
reduce()
forEach()
forEachOrdered()
min()
max()
anyMatch()
allMatch()
noneMatch()
findAny()
findFirst()

In further this article, we will be showing example programs on each operations.

3. Stream toArray() Method Example


Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

This will convert a stream into Object[] array or into a specified array to the IntFunction.

Syntax:

Object[] toArray()
<A> A[] toArray(IntFunction<A[]> generator)

Example:

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

Object[] objArray = stream.toArray();
System.out.println("objArray length " + objArray.length);
 
Output:

objArray length 5

4. Stream collect() Method Example


collect() method is the one most used in stream pipeline at the end. This method is used to collect the output of the Stream into List or Set or to perform groupingby and partioningby operations on the stream.
We have covered all possible operations on collect() method in the previous article.

Java 8 Stream Collectors API working examples.

Syntax:


<R,​A> R collect​(Collector<? super T,​A,​R> collector)

Example:

Stream<Integer> streamCOllect = Stream.of(1, 2, 3, 4, 5);

List<Integer> intList = streamCOllect.collect(Collectors.toList());
Set<Integer> intSet = streamCOllect.collect(Collectors.toSet());
Long count = streamCOllect.collect(Collectors.counting());

Output:

We will get the count or size 5 for all statements.

6. Stream count() Method Example


This method count of elements in this stream.

Syntax:

long count()

Simply returns the long value for the stream.

Example:

// Stream count() Method Example
Stream<Integer> streamCount = Stream.of(1, 2, 3, 4, 5);
long count = streamCount.count();
System.out.println("count :: " + count);

Output:

count :: 5

This is a special case of a reduction and is equivalent to:

return mapToLong(e -> 1L).sum();

7. Stream reduce() Example


Wherever we need to perform the one operation multiple times and finally it produces one result such as min, max, avg, sum. In these scenarios reduce() method is very useful.

Syntax:

Optional<T> reduce(BinaryOperator<T> accumulator)

Example:

To find the sum of the first 5 integers from the stream.


// Stream count() Method Example
Stream<Integer> streamReduce = Stream.of(1, 2, 3, 4, 5);
Optional<Integer> sum = streamReduce.reduce((value1, value2) -> value1 + value2);
System.out.println("sum of first 5 numbers using reduce opration : " + sum.get());

Output:


sum of first 5 numbers using reduce opration : 15  

7. Stream forEach() Example


This is very useful while debugging to print the values of the stream. This is used to perform one action on each value of stream and finally returns nothing.

Syntax:

void forEach(Consumer<? super T> action)

This takes Consumer Functional Interface as an argument.

Example:


// Stream forEach() Method Example
Stream<Integer> streamForEach = Stream.of(1, 2, 3, 4, 5);
// Printing the values
streamForEach.forEach(value -> System.out.println(value));

// Adding values to list.
List<Integer> numList = new ArrayList<>();
streamForEach.forEach(value -> numList.add(value));
System.out.println("numList : " + numList);

Output:
3
5
4
1
2
numList : [3, 5, 1, 4, 2]


Note: This works for both sequential and parellel streams.


8. Stream forEachOrdered() Example


This method works similarly to the forEach() but it executes the order they appear in the stream. This ignores the parallel() method invocation.

Syntax:


void forEachOrdered(Consumer<? super T> action)

Example:


// Stream streamForEachOrdered() Method Example
Stream<Integer> streamForEachOrdered = Stream.of(1, 2, 3, 4, 5).parallel();
// Printing the values
streamForEachOrdered.forEachOrdered(value -> System.out.println(value));

// Adding values to list.
Stream<Integer> streamForEachOrderedList = Stream.of(1, 2, 3, 4, 5).parallel();
List<Integer> numList1 = new ArrayList<>();
streamForEachOrderedList.forEachOrdered(value -> numList1.add(value));
System.out.println("numList1 : " + numList1);
Output:
1
2
3
4
5
numList1 : [1, 2, 3, 4, 5]

Compare the output with forEach() method output and see the order.

9. Stream min() Example


min() method returns the minimum element of this stream according to the provided Comparator. This does first sorting and takes the first element from the sorted array.

Syntax:

Optional<T> min(Comparator<? super T> comparator)

Example:
// Stream min() Method Example
Stream<Integer> streamMin = Stream.of(1, 2, 3, 4, 5).parallel();
Optional<Integer> min = streamMin.min((v1, v2) -> v1.compareTo(v2));
System.out.println("Min value : " + min.get());

Output:
Min value : 1

10. Stream max() Example


This method returns the maximum element of this stream according to the provided Comparator. This internally does sorting first and get the last element from it. If the stream is having large data set then better not to use this.

Syntax:
Optional<T> max(Comparator<? super T> comparator)

Example:
// Stream max() Method Example
Stream<Integer> streamMax = Stream.of(1, 2, 3, 4, 5).parallel();
Optional<Integer> max = streamMax.max((v1, v2) -> v1.compareTo(v2));
System.out.println("Max value : " + max.get());

Output:

Max value : 5

11. Stream anyMatch() Example


This method checks the predicate condition. If any value in the stream matches to the given predicate then it returns true else false.

Predicate is a functional interface that holds the condition.

Predicate p = value -> value > 0;

Syntax:
boolean anyMatch(Predicate<? super T> predicate)

Example:
// Stream anymatch() Method Example
Stream<Integer> streamAnymatch = Stream.of(1, 2, 3, 4, 5).parallel();
Predicate<Integer> anymatch = value -> value > 4;
boolean isAnymatch = streamAnymatch.anyMatch(anymatch);
System.out.println("anymatch value : " + isAnymatch);


Output:
anymatch value : true

If the stream is empty then returns false and predicate condition is not evaluated.

12. Stream allMatch() Example


This method also takes a predicate as an argument. Predicate holds a condition. If all values of stream match to the given predicate then it returns true else false.


Syntax:
boolean allMatch(Predicate<? super T> predicate)

Example:
// Stream allmatch() Method Example 
Stream<Integer> streamAllmatch = Stream.of(1, 2, 3, 4, 5).parallel();
Predicate<Integer> allmatch = value -> value > 2;
boolean isAllmatch = streamAllmatch.allMatch(allmatch);
System.out.println("allmatch value : " + isAllmatch);

Output:
allmatch value : false

If the stream is empty then returns true and predicate condition is not evaluated.


13. Stream noneMatch() Example


This takes a predicate as an argument. If all of the stream elements do not match the predicate condition then it returns true else false.

Syntax:
boolean noneMatch(Predicate<? super T> predicate)

Example:
// Stream noneMatch() Method Example
Stream<Integer> streamNoneMatch = Stream.of(1, 2, 3, 4, 5).parallel();
Predicate<Integer> nonematch = value -> value > 7;
boolean isNoneMatch = streamNoneMatch.noneMatch(nonematch);
System.out.println("noneMatch method returned value : " + isNoneMatch);

Output:
noneMatch method returned value : true



See the above output and printed it as true. because the predicate condition is value greater than 7 and all values are below 7. No con
If the stream is empty then returns true and predicate condition is not evaluated.

14. Stream findAny() Example


This will be getting the value randomly from the stream. That's why the method is named findAny if any value present in the stream.
The value will be returned as an Optional object. If the stream is empty then it returns empty Optional object.

Syntax:
Optional<T> findAny()

Example:
// Stream findAny() Method Example
Stream<Integer> streamFindAny = Stream.of(1, 2, 3, 4, 5).parallel();
Predicate<Integer> findAny = value -> value % 2 == 1;
Optional<Integer> findAnyOpt = streamFindAny.filter(findAny).findAny();
System.out.println("Find any odd number : " + findAnyOpt.get());

Output:
Find any odd number : 5

Here 5 is picked up by findAny() method. If we run multiple times then it will return 1 or 3.

15. Stream findFirst() Example


This method get the first value always from stream. The value is returned as an instance of Optional. If the stream is empty them returns empty Optional object.

Syntax:
Optional<T> findFirst()

Example:
// Stream findFirst() Method Example
Stream<Integer> streamFindFirst = Stream.of(1, 2, 3, 4, 5).parallel();
Predicate<Integer> findFirst = value -> value % 2 == 0;
Optional<Integer> findFirstOpt = streamFindFirst.filter(findFirst).findFirst();
System.out.println("Find first odd number : " + findFirstOpt.get());

Output:
Find first odd number : 2

If we call findFirst() multiple times and it will return always value 2.

16. Full Examples Program


All the examples are shown in the single java program with output.

package com.java.w3schools.blog.java8.streams;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Stream api terminal operations of java 8
 * 
 * @author java-w3schools
 *
 */
public class StreamTerminalOperations {

 public static void main(String[] args) {

  Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

  // Stream toArray() Method Example
  Object[] objArray = stream.toArray();
  System.out.println("objArray length " + objArray.length);

  // Stream collect() Method Example
  Stream<Integer> streamCOllect = Stream.of(1, 2, 3, 4, 5);

  List<Integer> intList = streamCOllect.collect(Collectors.toList());
  // Set<Integer> intSet = streamCOllect.collect(Collectors.toSet());
  // Long count = streamCOllect.collect(Collectors.counting());

  // Stream count() Method Example
  Stream<Integer> streamCount = Stream.of(1, 2, 3, 4, 5);
  Long count = streamCount.count();
  System.out.println("count :: " + count);

  // Stream count() Method Example
  Stream<Integer> streamReduce = Stream.of(1, 2, 3, 4, 5);
  Optional<Integer> sum = streamReduce.reduce((value1, value2) -> value1 + value2);
  System.out.println("sum of first 5 numbers using reduce opration : " + sum.get());

  // Stream forEach() Method Example
  Stream<Integer> streamForEach = Stream.of(1, 2, 3, 4, 5).parallel();
  // Printing the values
  // streamForEach.forEach(value -> System.out.println(value));

  // Adding values to list.
  List<Integer> numList = new ArrayList<>();
  streamForEach.forEach(value -> numList.add(value));
  System.out.println("numList : " + numList);

  // Stream streamForEachOrdered() Method Example
  Stream<Integer> streamForEachOrdered = Stream.of(1, 2, 3, 4, 5).parallel();
  // Printing the values
  streamForEachOrdered.forEachOrdered(value -> System.out.println(value));

  // Adding values to list.
  Stream<Integer> streamForEachOrderedList = Stream.of(1, 2, 3, 4, 5).parallel();
  List<Integer> numList1 = new ArrayList<>();
  streamForEachOrderedList.forEachOrdered(value -> numList1.add(value));
  System.out.println("numList1 : " + numList1);

  // Stream min() Method Example
  Stream<Integer> streamMin = Stream.of(1, 2, 3, 4, 5).parallel();
  Optional<Integer> min = streamMin.min((v1, v2) -> v1.compareTo(v2));
  System.out.println("Min value : " + min.get());

  // Stream max() Method Example
  Stream<Integer> streamMax = Stream.of(1, 2, 3, 4, 5).parallel();
  Optional<Integer> max = streamMax.max((v1, v2) -> v1.compareTo(v2));
  System.out.println("Max value : " + max.get());

  // Stream anymatch() Method Example
  Stream<Integer> streamAnymatch = Stream.of(1, 2, 3, 4, 5).parallel();
  Predicate<Integer> anymatch = value -> value > 4;
  boolean isAnymatch = streamAnymatch.anyMatch(anymatch);
  System.out.println("anymatch value : " + isAnymatch);

  // Stream allmatch() Method Example
  Stream<Integer> streamAllmatch = Stream.of(1, 2, 3, 4, 5).parallel();
  Predicate<Integer> allmatch = value -> value > 2;
  boolean isAllmatch = streamAllmatch.allMatch(allmatch);
  System.out.println("allmatch value : " + isAllmatch);

  // Stream noneMatch() Method Example
  Stream<Integer> streamNoneMatch = Stream.of(1, 2, 3, 4, 5).parallel();
  Predicate<Integer> nonematch = value -> value > 7;
  boolean isNoneMatch = streamNoneMatch.noneMatch(nonematch);
  System.out.println("noneMatch method returned value : " + isNoneMatch);

  // Stream findAny() Method Example
  Stream<Integer> streamFindAny = Stream.of(1, 2, 3, 4, 5).parallel();
  Predicate<Integer> findAny = value -> value % 2 == 1;
  Optional<Integer> findAnyOpt = streamFindAny.filter(findAny).findAny();
  System.out.println("Find any odd number : " + findAnyOpt.get());

  // Stream findFirst() Method Example
  Stream<Integer> streamFindFirst = Stream.of(1, 2, 3, 4, 5).parallel();
  Predicate<Integer> findFirst = value -> value % 2 == 0;
  Optional<Integer> findFirstOpt = streamFindFirst.filter(findFirst).findFirst();
  System.out.println("Find first odd number : " + findFirstOpt.get());

 }

}
Output:
objArray length 5
count :: 5
sum of first 5 numbers using reduce opration : 15
numList : [3, 1, 4, 2, 5]
1
2
3
4
5
numList1 : [1, 2, 3, 4, 5]
Min value : 1
Max value : 5
anymatch value : true
allmatch value : false
noneMatch method returned value : true
Find any odd number : 1
Find first odd number : 2

17. Conclusion


In this article, We've seen the complete list of java 8 stream terminal operations. Stream API has a total of 14 Terminal Operations.

Shown all methods with example programs.

GitHub

API Ref

Stream API


How to Join or Merge two lists in java 8?


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - 14 Stream Terminal Operations With Examples
Java 8 - 14 Stream Terminal Operations With Examples
Java 8 Stream API code with practical working examples for all terminal operations.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGk1y1lPQY8Ces3sAQo5QIhRUru39ePri4Du-7VRvCaATCrZzjMxi0shCYWXKH8UKkpOm6gZ-wnnk5DiLxFezMe0ZkumoV21lbp94nOshdX1efZc5eG_rIcBPNAfgdL9O4Go342FVM0Mk/s640/Java+8+-+14+Stream+Terminal+Operations+With+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGk1y1lPQY8Ces3sAQo5QIhRUru39ePri4Du-7VRvCaATCrZzjMxi0shCYWXKH8UKkpOm6gZ-wnnk5DiLxFezMe0ZkumoV21lbp94nOshdX1efZc5eG_rIcBPNAfgdL9O4Go342FVM0Mk/s72-c/Java+8+-+14+Stream+Terminal+Operations+With+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/java-8-14-stream-terminal-operations.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/java-8-14-stream-terminal-operations.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content