Java – How to sum all the stream integers

The sum() method is available in the primitive int-value stream like IntStream, not Stream<Integer>. We can use mapToInt() to convert a stream integers into a IntStream.


int sum = integers.stream().mapToInt(Integer::intValue).sum();
int sum = integers.stream().mapToInt(x -> x).sum();

Full example.

Java8Stream.java

package com.mkyong.concurrency;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class Java8Stream {

    public static void main(String[] args) {

        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        int sum = integers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Total : " + sum);

        Stream<Integer> integers2 = Stream.iterate(1, n -> n + 1).limit(10);
        IntStream intStream = integers2.mapToInt(x -> x);
        int sum1 = intStream.sum();
        System.out.println("Total : " + sum1);

    }

}

Output


Total : 55
Total : 55

References

  1. Oracle doc – IntStream.html

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar