问题
How would you find the sum of the elements of a set in Java? Would it be the same with an array?
In python, I could do:
my_set = {1, 2, 3, 4}
print(sum(my_set))
回答1:
Aside from using loops explicitly, for List<Integer> list
you can do:
int sum = list.stream().mapToInt(Integer::intValue).sum();
If it's an int[] ar
then do:
int sum = IntStream.of(ar).sum();
This is based on the use of streams.
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;
}
回答2:
int sum = 0;
for( int i : my_set) {
sum += i;
}
System.out.println(sum);
回答3:
Here is simple example to get sum of list elements.
public static void main(String args[]){
int[] array = {10, 20, 30, 40, 50};
int sum = 0;
for(int num : array) {
sum = sum+num;
}
System.out.println("Sum of array elements is:"+sum);
}
Output :
Sum of array elements is:150
Hope this solution helpful you to understand the concept.
来源:https://stackoverflow.com/questions/58811850/how-do-you-find-the-sum-of-all-numbers-in-a-set-in-java