【问题标题】:Get the product of a list using java Lambdas使用 java Lambdas 获取列表的乘积
【发布时间】:2016-05-13 23:22:16
【问题描述】:

如何使用 java Lambdas 获得数组的乘积。我知道在 C# 中是这样的:

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

编辑:使问题更清楚。

【问题讨论】:

标签: java lambda java-stream


【解决方案1】:
list.stream().reduce(1, (a, b) -> a * b);

【讨论】:

  • 问题有点混乱,说list,但代码说array,所以可能同时显示?
  • 另一种语言的示例使用array,但其他所有内容都要求列表的乘积。
  • 另外,reduce((a, b) -> b * a).orElseXxx() 在技术上更接近显示的 C# 版本,虽然我不知道哪个 orElseXxx() 方法是合适的,因为 C# 文档似乎没有描述空调用时的结果输入。
  • @Andreas,它最接近reduce(...).get()。见here
【解决方案2】:

您同时提到了数组和列表,所以这两种方法都适用:

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

如果列表/数组可能为空,则该版本有一个缺点:如果列表或数组为空,则第一个参数 1 在这种情况下将作为结果返回,所以如果您不希望这样行为,有一个版本会返回Optional<Integer>、OptionalInt 等:

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

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多