Stream.reduce() in Java with examples
Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements.
reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.
Syntax :
T reduce(T identity, BinaryOperator<T> accumulator);
Where, identity is initial value
of type T and accumulator is a
function for combining two values.
sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.
Let us see some examples to understand the reduce() function in a better way :
Example 1 :
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<String> words = Arrays.asList( "GFG" , "Geeks" , "for" ,
"GeeksQuiz" , "GeeksforGeeks" );
Optional<String> longestString = words.stream()
.reduce((word1, word2)
-> word1.length() > word2.length()
? word1 : word2);
longestString.ifPresent(System.out::println);
}
}
|
Output :
GeeksforGeeks
Example 2 :
import java.util.*;
class GFG {
public static void main(String[] args)
{
String[] array = { "Geeks" , "for" , "Geeks" };
Optional<String> String_combine = Arrays.stream(array)
.reduce((str1, str2)
-> str1 + "-" + str2);
if (String_combine.isPresent()) {
System.out.println(String_combine.get());
}
}
}
|
Output :
Geeks-for-Geeks
Example 3 :
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> array = Arrays.asList(- 2 , 0 , 4 , 6 , 8 );
int sum = array.stream().reduce( 0 ,
(element1, element2) -> element1 + element2);
System.out.println( "The sum of all elements is " + sum);
}
}
|
Output :
The sum of all elements is 16
Example 4 :
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args)
{
int product = IntStream.range( 2 , 8 )
.reduce((num1, num2) -> num1 * num2)
.orElse(- 1 );
System.out.println( "The product is : " + product);
}
}
|
Output :
The product is : 5040
Last Updated :
16 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...