Create Int Stream and use Reduce Method on it in java 8



Program/ Example - create Int Stream and use Reduce Method on it in java 8
/**
* Write a program to - create Int Stream and use Reduce Method on it in java 8
*/
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class IntStreamReduceMethodExample {
   public static void main(String[] args) {
         
          System.out.println("Create IntStream");
          IntStream streamOfIntegers = IntStream.of(1, 2, 3, 4);
          System.out.println("Use reduce() method - to calculate sum of Integers in IntStream");
          //reduce() method will reduce stream to calculate sum of Integers in IntStream
          OptionalInt optionalInteger = streamOfIntegers.reduce((i1, i2) -> i1 + i2);
          //Display optionalInteger
          System.out.println("sum = "+optionalInteger.getAsInt()); //get() returns the value.
   }
}
/* OUTPUT
Create IntStream
Use reduce() method - to calculate sum of Integers in IntStream
sum = 10
*/


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.







eEdit
Must read for you :