Search code examples
javasumset

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


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)) 

Solution

  • 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;
    }