-1

I was wondering what the best way to sum the elements of an integer list in java is.

I'm aware I could perform this with a for loop but I was expecting there might be inbuilt ways to do this, such as the reduce function in other languages.

The relevant code for this problem has been provided below.

  public static int sumList(List<Integer> list) {
    return 0; //should return sum of integers in list
  }
Hiphop03199
  • 729
  • 3
  • 16

1 Answers1

7

You can use the Stream API in Java 8

return list.stream().mapToInt(i -> i).sum();

The .mapToInt(i -> i) is required as Java doesn't know how to sum any object but it does know how to sum an IntStream and this converts the Stream<Integer> into an IntStream

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130