Create stream of Integers and use Reduce Method on it in java 8



Program/ Example - create streamOfIntegers and use Reduce Method on it in java 8
/**
* Write a program to - create streamOfIntegers and use Reduce Method on it in java 8
*/
import java.util.Optional;
import java.util.stream.Stream;
public class StreamOfIntegerReduceMethod {
   public static void main(String[] args) {
          System.out.println("Create Stream of Integers");
          Stream<Integer> streamOfIntegers = Stream.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 numbers
          Optional<Integer> optionalInteger = streamOfIntegers.reduce((i1, i2) -> i1 + i2);
          //Display optionalInteger
          System.out.println("sum = "+optionalInteger.get()); //get() returns the value.
   }
}
/* OUTPUT
Create Stream of Integers
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 :