How to Sum Stream Integers in Java


In this example, we will useĀ Stream.iterate() to sum integers.

Source Code

package com.beginner.examples;

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

public class SumStreamExample {

    public static void main(String[] args){
    	// use Stream.iterate()
    	Stream integers = Stream.iterate(1, i -> i + 2).limit(2);
        //use mapToInt() to convert a stream integers into a IntStream.
        IntStream intStream = integers.mapToInt(x -> x);
        int sum1 = intStream.sum();
        System.out.println("Sum : " + sum1);
        
        // use Arrays.asList()
    	List ints = Arrays.asList(1, 3);    	
    	//use mapToInt() to convert a stream integers into a IntStream.
        int sum = ints.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Sum : " + sum);

        
    }
}

Output:

Sum : 4
Sum : 4

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments