Java Stream reduce()与实例

Java Stream reduce()与实例

很多时候,我们需要执行一些操作,将一个流减少到单一的结果值,例如,最大、最小、总和、积等。减少是将所有元素组合起来的重复过程。

reduce操作对流中的每个元素应用一个二进制运算符,运算符的第一个参数是前一个应用的返回值,第二个参数是当前流元素。

语法:

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()等是一些减少操作的例子。 reduce()明确要求你指定如何减少通过流的数据。

让我们看一些例子来更好地理解reduce()函数:
例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", "Geeks", "for",
                                           "GeeksQuiz", "GeeksforGeeks");
  
        // 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);
    }
}

输出:

GeeksforGeeks

例2 :

// Implementation of reduce method
// to get the combined String
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // String array
        String[] array = { "Geeks", "for", "Geeks" };
  
        // The result of the reduce() method is
        // an Optional because the list on which
        // reduce() is called may be empty.
        Optional<String> String_combine = Arrays.stream(array)
                                           .reduce((str1, str2)
                                           -> str1 + "-" + str2);
  
        // Displaying the combined String
        if (String_combine.isPresent()) {
            System.out.println(String_combine.get());
        }
    }
}

输出:

Geeks-for-Geeks

例3 :

// Implementation of reduce method
// to get the sum of all elements
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating list of integers
        List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8);
  
        // Finding sum of all elements
        int sum = array.stream().reduce(0,
                (element1, element2) -> element1 + element2);
  
        // Displaying sum of all elements
        System.out.println("The sum of all elements is " + sum);
    }
}

输出:

The sum of all elements is 16

例4 :

// Implementation of reduce method
// to get the product of all numbers
// in given range.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To get the product of all elements
        // in given range excluding the
        // rightmost element
        int product = IntStream.range(2, 8)
                     .reduce((num1, num2) -> num1 * num2)
                     .orElse(-1);
  
        // Displaying the product
        System.out.println("The product is : " + product);
    }
}

输出:

The product is : 5040

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程