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. 

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. 

sum() is terminal operation which returns sum of elements in a stream.

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete