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,

Comments

Popular posts from this blog

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

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

Java - DES Encryption and Decryption example

Java - Blowfish Encryption and decryption Example

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

ReactJS - Bootstrap - Buttons

Top 5 Java ORM tools - 2024

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String