你如何在Java中找到集合中所有数字的总和? [英] How do you find the sum of all numbers in a set in Java?

查看:147
本文介绍了你如何在Java中找到集合中所有数字的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中如何求集合的元素之和?数组也一样吗?

How would you find the sum of the elements of a set in Java? Would it be the same with an array?

在python中,我可以:

In python, I could do:

my_set = {1, 2, 3, 4} 
print(sum(my_set)) 

推荐答案

除了显式使用循环之外,对于 List列出你可以做的:

Aside from using loops explicitly, for List<Integer> list you can do:

int sum = list.stream().mapToInt(Integer::intValue).sum();

如果它是一个 int[] ar 然后做:

If it's an int[] ar then do:

int sum = IntStream.of(ar).sum();

这是基于的使用.

或者你可以做这个简单的单线循环:

Or you can do this simple one liner loop:

int sum = 0;
for (Integer e : myList) sum += e;

更好的是,编写一个函数并重用它:

Even better, write a function and reuse it:

public int sum(List<Integer> list) {
    int sum = 0;
    for (Integer e : list) sum += e;

    return sum;
}

这篇关于你如何在Java中找到集合中所有数字的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆