How do you find the sum of all numbers in a set in Java? [duplicate]

廉价感情. 提交于 2021-01-26 02:57:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!