Pages

Sunday, November 15, 2020

Java 8 - 14 Stream Terminal Operations With Examples

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?


No comments:

Post a Comment

Please do not add any spam links in the comments section.