简体   繁体   中英

Get the product of a list using java Lambdas

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[] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM