In Stream reduce method, must the identity always be 0 for sum and 1 for multiplication?

前端 未结 7 854
执念已碎
执念已碎 2020-11-29 06:05

I proceed with java 8 learning.

I have found an interesting behavior:

let\'s see code sample:

// identity value and accumulator and combiner         


        
7条回答
  •  隐瞒了意图╮
    2020-11-29 06:34

    Yes, you are breaking the contract of the combiner function. The identity, which is the first element of reduce, must satisfy combiner(identity, u) == u. Quoting the Javadoc of Stream.reduce:

    The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u) is equal to u.

    However, your combiner function performs an addition and 1 is not the identity element for addition; 0 is.

    • Change the identity used to 0 and you will have no surprise: the result will be 72 for the two options.

    • For your own amusement, change your combiner function to perform a multiplication (keeping the identity to 1) and you will also notice the same result for both options.

    Let's build an example where the identity is neither 0 or 1. Given your own domain class, consider:

    System.out.println(Person.getPersons().stream()
                        .reduce("", 
                                (acc, p) -> acc.length() > p.name.length() ? acc : p.name,
                                (n1, n2) -> n1.length() > n2.length() ? n1 : n2));
    

    This will reduce the stream of Person to the longest person name.

提交回复
热议问题