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

前端 未结 7 870
执念已碎
执念已碎 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:48

    The identity value is a value, such that x op identity = x. This is a concept which is not unique to Java Streams, see for example on Wikipedia.

    It lists some examples of identity elements, some of them can be directly expressed in Java code, e.g.

    • reduce("", String::concat)
    • reduce(true, (a,b) -> a&&b)
    • reduce(false, (a,b) -> a||b)
    • reduce(Collections.emptySet(), (a,b)->{ Set s=new HashSet<>(a); s.addAll(b); return s; })
    • reduce(Double.POSITIVE_INFINITY, Math::min)
    • reduce(Double.NEGATIVE_INFINITY, Math::max)

    It should be clear that the expression x + y == x for arbitrary x can only be fulfilled when y==0, thus 0 is the identity element for the addition. Similarly, 1 is the identity element for the multiplication.

    More complex examples are

    • Reducing a stream of predicates

      reduce(x->true, Predicate::and)
      reduce(x->false, Predicate::or)
      
    • Reducing a stream of functions

      reduce(Function.identity(), Function::andThen)
      

提交回复
热议问题