-3

How do you get the product of a array using java Lambdas. I know in C# it is like this:

result = array.Aggregate((a, b) => b * a);

edit: made the question more clear.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Sepehr Sobhani
  • 862
  • 3
  • 12
  • 29
  • 1
    This operation is called "reduction". Tutorial here: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html – dnault May 13 '16 at 23:32

2 Answers2

6
list.stream().reduce(1, (a, b) -> a * b);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Question is a bit confusing, saying `list`, but code saying `array`, so maybe show both? – Andreas May 13 '16 at 23:41
  • The example from another language uses `array`, but everything else asks for the product of a list. – Louis Wasserman May 13 '16 at 23:43
  • Also, `reduce((a, b) -> b * a).orElseXxx()` is technically closer to the C# version shown, though I don't know which `orElseXxx()` method is appropriate, since C# documentation doesn't seem to describe result when called on empty input. – Andreas May 13 '16 at 23:51
  • 1
    @Andreas, it would be closest to `reduce(...).get()`. See [here](http://stackoverflow.com/questions/8867867/sequence-contains-no-elements-exception-in-linq-without-even-using-single). – shmosel May 13 '16 at 23:55
0

You mention both arrays and lists, so here is how you would do it for both:

Integer intProduct = list.stream().reduce(1, (a, b) -> a * b);   
Integer intProduct = Arrays.stream(array).reduce(1, (a, b) -> a * b);  // Integer[]
int intProduct = Arrays.stream(array).reduce(1, (a, b) -> a * b);  // int[]

That version has one drawback if the list/array might be empty: the first argument, 1 in this case, will be returned as the result if the list or array are empty, so if you don't want that behavior, there is a version that will return an Optional<Integer>, OptionalInt, etc.:

Optional<Integer> intProduct = list.stream().reduce((a, b) -> a * b);   
Optional<Integer> intProduct = Arrays.stream(array).reduce((a, b) -> a * b);  // Integer[] 
OptionalInt intProduct = Arrays.stream(array).reduce((a, b) -> a * b);  // int[] 
Hank D
  • 6,271
  • 2
  • 26
  • 35