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.
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.
list.stream().reduce(1, (a, b) -> a * b);
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[]