使用Java Streams从List<List<Integer>>中计算所有对角线元素的和?

huangapple go评论70阅读模式
英文:

Sum of all diagonal elements from List<List<Integer>> using java streams?

问题

如何使用Java流(Java streams)获取二维整型列表 List<List<Integer>> 中所有对角线元素的和?

英文:

How to get sum of all diagonal elements in List of lists List&lt;List&lt;Integer&gt;&gt; using java streams?

答案1

得分: 1

int diagonalSum(List<List<Integer>> matrix) {
    int n = matrix.size();
    return IntStream.range(0, n)
        .map(i -> i < matrix.get(i).size() ? matrix.get(i).get(i).intValue() : 0)
        .sum();
}

就像是一个for循环一样:`IntStream.range` 用于行和列的索引也可以添加 `.parallel()`,不过是否更高效需要进行衡量
英文:
int diagonalSum(List&lt;List&lt;Integer&gt;&gt; matrix) {
    int n = matrix.size();
    return IntStream.range(0, n)
        .map(i -&gt; i &lt; matrix.get(i).size() ? matrix.get(i).get(i).intValue() : 0)
        .sum();
}

Just the same as a for loop: IntStream.range for a row&column index. One might add .parallel() though whether that is more efficient must be measured.

答案2

得分: 1

感谢Joop,看起来我之前尝试的方向不对,我试着使用了列表流(List streams),但这个方法更简洁。所以这个问题的最终一行解决方案是:

IntStream.range(0, test.size()).map(i -> test.get(i).get(i)).sum();
英文:

Thanks Joop, looks like I was trying in another direction, was trying with List streams but this one is clean.
So final one line solution for this is,

IntStream.range(0, test.size()).map(i -&gt; test.get(i).get(i)).sum();

huangapple
  • 本文由 发表于 2020年10月13日 18:11:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64333171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定