Java 8 Streams - Sum of all the items of the List
Example 1: Using Collectors.summingInt()
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.collect(Collectors.summingInt(Integer::intValue));
System.out.println("Sum= " + sum);
}
}
Here, stream() method returns a sequential Stream with List as its source.
summingInt() method returns a Collector that produces the sum of a integer.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.collect(Collectors.summingInt(Integer::intValue));
System.out.println("Sum= " + sum);
}
}
Similarly, the Collectors class provides summingDouble() and summingLong().
Example 2: Using Stream.reduce()
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum="+sum);
}
}
reduce() is terminal operations, here it helps us to sum all elements of list.
Example 3: Using IntStream.sum()
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum= " + sum);
}
}
Here mapToInt() method convert Stream of Integer to IntStream.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(2, 9, 10, 8, 4, 7);
Integer sum = integers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum= " + sum);
}
}
sum() is terminal operation which returns sum of elements in a stream.
More related topics,