Thursday 10 August 2017

How to use Java 8 streams reduction operations sum, count, and average| Streams in Java 8


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=22Ypxfqs0ZI&list=UUhwKlOVR041tngjerWxVccw

StreamDemo.java
import java.util.Arrays;
import java.util.OptionalDouble;

/**
 * 
 * A reduction operation is one which allows you to compute a result
 * using all the elements present in a stream.
 * 
 * Reduction operations are also called terminal operations because
 * they are always present at the end of a chain of Stream methods
 * 
 * Java 8 includes several reduction methods, such as sum, average and
 * count, which allow to perform arithmetic operations on Stream
 * objects and get numbers as results.
 */
public class StreamDemo
{
    public static void main(String[] args)
    {
        int[] numberArray = { 2, 6, 8 };
        int sum = Arrays.stream(numberArray).sum();
        System.out.println("sum = " + sum);

        long count = Arrays.stream(numberArray).count();
        System.out.println("count = " + count);

        OptionalDouble optionalDouble = Arrays.stream(numberArray).average();
        System.out.println("average = " + optionalDouble.getAsDouble());
    }
}
Output
sum = 16
count = 3
average = 5.333333333333333

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_reduction_sca_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_reduction_sca_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/ed01c4e942c222c96b1953312e7a54d5a8556409/BasicJava/StreamDemo_reduction_sca_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment