-2

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
  • 744
  • 2
  • 11
  • 26

3 Answers3

7

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,864
  • 1
  • 12
  • 21
2
int sum = 0;
for( int i : my_set) {
    sum += i;
}

System.out.println(sum);
  • Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Sep 01 '23 at 13:20
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
  • 411
  • 6
  • 28