functional programming - Is it possible to iterate a stream only once and perform 2 or more operations? -


given code

list<integer> numbers = arrays.aslist(2, 4, 3);  int sumtotal = numbers.stream().reduce(-3, (x, y) -> x + y + 3); int multiplytotal = numbers.stream().reduce(1, (x, y) -> x * y); 

is possible perform both operations while iterating stream once?

also, notice each reduce has different identity: -3 , 1.

you can create custom class, , use mutable reduction:

public static void main(string[] args) {     list<integer> numbers = arrays.aslist(2, 4, 3);      result result = numbers.stream().collect(result::new, result::consume, result::combine);     system.out.println("result = " + result); }  private static class result {     private int sum = 0;     private int product = 1;      public void consume(int i) {         sum += + 3;         product *= i;     }      public void combine(result r) {         // read note below         sum += r.sum + 3;         product *= r.product;     }      @override     public string tostring() {         return "result{" +             "sum=" + sum +             ", product=" + product +             '}';     } } 

but doubt gain doing on iterating twice you're doing.

edit:

note combine() method above, invoked when using parallel stream, produce results inconsistent sequential stream. problem caused, holger mentions in comments, fact operation doesn't respect identity preconditions of reduction: applying reduction on value v identity supposed produce v, produces v + 3 0 identity.

make sure not use parallel stream compute result.


Comments