The reduce() method in Java8 Stream, which performs aggregation operations

When I first learned about the reduce() method in Stream, I was in the process of brushing the algorithm questions recently (described below), and the concise and succinct way of writing made my eyes shine.

So, I simply learned and summarized the writing method:


text

The Java 8 API adds a new abstraction called Stream that allows you to process data in a declarative way.

The Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code.

This style treats the set of elements to be processed as a kind of stream, the stream is transmitted in the pipeline, and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.

reduce() use:

Let's take a look inside the reduce() method. The parameter BinaryOperator<T> interface inherits the BiFunction interface:

Optional<T> reduce(BinaryOperator<T> accumulator);

In simple terms, the BinaryOperator functional interface is similar to a lambda expression (->), which accepts two parameters and produces a result, except that its three parameters are all of the same data type.

@Data
public class User {
    private String username;
    private String gender;
    private Integer age;
    public User(){}

    public User(String username, String gender, Integer age) {
        this.username = username;
        this.gender= gender;
        this.age = age;
    }

    public static void main(final String... args) {
        ArrayList<User> list = new ArrayList<>();

        list.add(new User("jimmy", "1", 30));
        list.add(new User("amy", "2", 20));
        list.add(new User("simmy", "1", 10));

        // reduce 需要传入一个BinaryOperator接口,继承了BiFunction接口
        // 简单说  就是需要传入2个同类型参数,返回同类型的参数
        // 预定义一下减法函数式
        BinaryOperator<Integer> add = (n1, n2) -> n1+n2;
        BinaryOperator<Integer> minus = (n1, n2) -> n1-n2;
        list.stream().map(n->n.getAge()).reduce(add).ifPresent(n-> System.out.println(n));     // 加法
        list.stream().map(n->n.getAge()).reduce(minus).ifPresent(n-> System.out.println(n));     // 减法

        // 未预定义,直接写函数式
        list.stream().map(n->n.getAge()).reduce((a,b)->a*b).ifPresent(n-> System.out.println(n));     // 乘法
    }
}
// 输出结果:
60
0
6000

algorithm problem

The following is a scenario where I use the reduce aggregate function, for reference:

Title: "Sword Pointing Offer" - Find Numbers that Appear Only Once
Title Description: Given a non-empty array of integers, except for a certain element that appears only once, every other element appears twice, find the number that only appears once Elements that appear once.
Idea: The XOR of two identical numbers is 0, the XOR of a number and 0 is still itself, and the XOR of A and B is obtained after the XOR of all numbers, and then the result of the XOR of 1 that appears on the far right of the number is obtained. index, and then determine whether each number is 1 after shifting index to the right.
    int[] nums = {1,2,3,4,5,6,7,8,9}

    // 1.for循环写法
    public int singleNumber_1(int[] nums) {
        int num = nums[0];
        for (int i = 1; i < nums.length; i++) {
            num ^= nums[i];
        }
        return num;
    }

    // 2.stream 写法
    public int singleNumber_2(int[] nums) {
        return Arrays.stream(nums).reduce((a, b) -> a^b).getAsInt();
    }

Take a look, is the stream's reduce aggregation function written concisely and concisely? Use it!


Guess you like

Origin blog.csdn.net/weixin_44259720/article/details/122603240
Recommended