Sum of list in Java

Java 8 Stream- Sum of List of Integers

By Atul Rai | Last Updated: November 3, 2019 Previous Next

Java 8 Stream interface provides mapToInt[] method to convert a stream integers into aIntStream object and upon calling sum[] method of IntStream, we can calculate the sum of a list of integers.

IntStream is available for primitive int-valued elements supporting sequential and parallel aggregate operations.

int total1 = listOfInteger.stream[].mapToInt[Integer::intValue].sum[]; int total2 = listOfInteger.stream[].mapToInt[i -> i].sum[]; // Bonus point :] int total3 = listOfInteger.stream[].collect[Collectors.summingInt[Integer::intValue]];

Lets see the full example.

Main.java

package org.websparrow; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Main { public static void main[String[] args] { List listOfInteger = Arrays.asList[8, 22, 02, 28]; // Java 8- method reference int total1 = listOfInteger.stream[].mapToInt[Integer::intValue].sum[]; System.out.println["Total 1:" + total1]; // Java 8- traditional way int total2 = listOfInteger.stream[].mapToInt[i -> i].sum[]; System.out.println["Total 2:" + total2]; // Java 8- Collectors: Bonus point:] int total3 = listOfInteger.stream[] .collect[Collectors.summingInt[Integer::intValue]]; System.out.println["Total 3:" + total3]; } }

Output

Total 1:60 Total 2:60 Total 3:60

References

  1. Interface Stream
  2. Interface IntStream
  3. Class Collectors

Java 8 stream sum

Previous

Next

Similar Posts

  • How to get file extension in Java
  • List of Thread class methods in Java
  • Java- Find all Capital Letters in the String
  • Java 8 Calculate date & time difference between two Zone
  • How to set and get Thread name in Java
  • Top 5 IDE for Java Developer
  • Java 8- How to replace word in a File using Stream
  • Core Java Interview Questions and Answers Part 5
  • Java- Find the index of the two numbers in the array whose sum is equal to a given number
  • Send email with attachment in Java using Gmail

About the Author

Atul RaiI love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.

Please enable JavaScript to view the comments powered by Disqus.

Video liên quan

Chủ Đề