英文:
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<List<Integer>>
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<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();
}
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 -> test.get(i).get(i)).sum();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论