Stream.reduce() in Java with examples Last Updated : 28 Aug, 2024 Comments Improve Suggest changes Like Article Like Report In Java, the Stream.reduce() method is used to perform a reduction on the elements of a stream using an associative accumulation function and returns an Optional. It is commonly used to aggregate or combine elements into a single result, such as computing the maximum, minimum, sum, or product. Syntax:T reduce(T identity, BinaryOperator<T> accumulator);identity: An initial value of type T.accumulator: A function that combines two values of type T.Examples of Stream.reduce() in JavaExample 1: Get the Longest String Java // Implementation of reduce method // to get the longest String import java.util.*; class GFG { public static void main(String[] args) { // Creating a list of Strings List<String> words = Arrays.asList("GFG", "Geeks", "for", "GeeksQuiz", "GeeksforGeeks"); // Using reduce to find the longest string in the list Optional<String> longestString = words.stream() .reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2); // Displaying the longest String longestString.ifPresent(System.out::println); } } OutputGeeksforGeeks Explanation:Purpose: Finds the longest string in the list.Lambda Expression: Compares two strings and returns the longer one.Result: An Optional because the list might be empty.Example 2: Combine Strings Java // Implementation of reduce method // to get the combined String import java.util.*; class GFG { public static void main(String[] args) { // String array to combine String[] array = { "Geeks", "for", "Geeks" }; // Using reduce to concatenate strings with a hyphen Optional<String> combinedString = Arrays.stream(array) .reduce((str1, str2) -> str1 + "-" + str2); // Displaying the combined String combinedString.ifPresent(System.out::println); } } OutputGeeks-for-Geeks Explanation:Purpose: Concatenates all strings in the array, separated by hyphens.Lambda Expression: Concatenates two strings with a hyphen.Result: An Optional because the stream might be empty.Example 3: Sum of All Elements Java // Implementation of reduce method // to get the sum of all elements import java.util.*; class GFG { public static void main(String[] args) { // Creating list of integers List<Integer> numbers = Arrays.asList(-2, 0, 4, 6, 8); // Using reduce to find the sum of all elements int sum = numbers.stream() .reduce(0, (element1, element2) -> element1 + element2); // Displaying the sum of all elements System.out.println("The sum of all elements is " + sum); } } OutputThe sum of all elements is 16 Explanation:Purpose: Computes the sum of all integers in the list.Lambda Expression: Adds each element to the accumulator.Identity Value: 0, which serves as the starting value.Example 4: Product of All Numbers in a Range Java // Implementation of reduce method // to get the product of all numbers // in given range. import java.util.*; import java.util.stream.IntStream; class GFG { public static void main(String[] args) { // Calculating the product of all numbers in the range [2, 8) int product = IntStream.range(2, 8) .reduce((num1, num2) -> num1 * num2) .orElse(-1); // Provides -1 if the stream is empty // Displaying the product System.out.println("The product is : " + product); } } OutputThe product is : 5040 Explanation:Purpose: Calculates the product of integers in the range [2, 8).Lambda Expression: Multiplies two numbers.Default Value: -1, used if the stream is empty.Key Points:The reduce method can be used for various reduction operations.The result of reduce is an Optional because the stream might be empty.reduce requires an associative operation to combine elements.When using reduce with a non-empty stream, specifying an identity value (like 0 for sum) simplifies the operation without needing to handle Optional.These examples and explanations demonstrate how to effectively use Stream.reduce() for different operations in Java. Comment More infoAdvertise with us Next Article Stream.reduce() in Java with examples S Sahil_Bansall Follow Improve Article Tags : Misc Java Java - util package Java-Functions java-stream Java-Stream interface +2 More Practice Tags : JavaMisc Similar Reads Stream mapToDouble() in Java with examples Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream. Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoke 2 min read Stream peek() Method in Java with Examples In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on ea 2 min read Stream min() method in Java with Examples Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a spec 3 min read Stream skip() method in Java with examples Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) 3 min read Stream.of(T t) in Java with examples Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple co 2 min read Stream count() method in Java with examples long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may travers 2 min read Stream mapToInt() in Java with examples Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream in 2 min read BitSet stream() Method in Java with Examples The stream() method of Java BitSet class is used to return a stream of indices for every bit contained in the BitSet. The indices are returned in increasing order. The size of the stream is the number of bits in the set state of the BitSet, which is equal to the value returned by the cardinality() m 2 min read Stream filter() in Java with examples Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but ins 3 min read Stream flatMap() in Java with examples Stream flatMap(Function mapper) returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMap(Function mapper) is an intermediate operation. These operations 5 min read Like