-3

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)) 
izhang05
  • 736
  • 1
  • 10
  • 24

3 Answers3

6

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[] arr then do:

int sum = IntStream.of(arr).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;
}
Javier Silva Ortíz
  • 2,624
  • 1
  • 10
  • 19
2
int sum = 0;
for( int i : my_set) {
    sum += i;
}

System.out.println(sum);
1

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.

Vimal
  • 401
  • 6
  • 28