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.
More Info: 1Z0-900: Java EE 7 Application Developer
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 :
// Implementation of reduce method
// to get the longest String
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a list of Strings
List<String> words = Arrays.asList("GFG", "LPI", "for",
"LPIQuiz", "LPIforLPI");
// The lambda expression passed to
// reduce() method takes two Strings
// and returns the longer String.
// The result of the reduce() method is
// an Optional because the list on which
// reduce() is called may be empty.
Optional<String> longestString = words.stream()
.reduce((word1, word2)
-> word1.length() > word2.length()
? word1 : word2);
// Displaying the longest String
longestString.ifPresent(System.out::println);
}
}
0 comments:
Post a Comment