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


i proceed java 8 learning.

i have found interesting behaviour:

lets see code sample:

// identity value , accumulator , combiner         integer summaryage = person.getpersons().stream()                 //.parallel()  //will return surprising result                 .reduce(1, (intermediateresult, p) -> intermediateresult + p.age,                         (ir1, ir2) -> ir1 + ir2);         system.out.println(summaryage); 

and model class:

public class person {      string name;      integer age;     ///...      public static collection<person> getpersons() {         list<person> persons = new arraylist<>();         persons.add(new person("vasya", 12));         persons.add(new person("petya", 32));         persons.add(new person("serj", 10));         persons.add(new person("onotole", 18));         return persons;    } } 

12+32+10+18 = 72
sequental stream code returns 73(72 + 1) parallel returns 76(72 + 4*1) always. 4 - stream elements count.

when saw result thought strange parallel stream , sequental streams returns different results.

am broke contract somewhere ?

p.s.

for me 73 expected result 76 - not.

the identity value value, such x op identity = x. concept not unique java streams, see example on wikipedia.

it lists examples of identity elements, of them can 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<x> s=new hashset<>(a); s.addall(b); return s; })
  • reduce(double.positive_infinity, math::min)
  • reduce(double.negative_infinity, math::max)

it should clear expression x + y == x arbitrary x can fulfilled when y==0, 0 identity element addition. similarly, 1 identity element multiplication.

more complex examples are

  • reducing stream of predicates

    reduce(x->true, predicate::and) reduce(x->false, predicate::or) 
  • reducing stream of functions

    reduce(function.identity(), function::andthen) 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -