//TestIntStream.java
//Illustrates the "old" way and the "new" way of doing some simple
//calculations, as well as some simple Java 8 "pipelines". Remember
//that a "pipeline" consists of source, zero or more intermediate
//operations, and a terminal operation.

import java.util.stream.IntStream;

public class TestIntStream
{
    public static void main(String[] args)
    {
        //Sum the first five positive integers
        //The old way, using an accumulator and a for-loop
        int sum = 0;
        for (int i = 1; i <= 5; i++)
        {
            sum = sum + i;
        }
        System.out.println(sum);

        //The new way, using a pipeline with zero intermediate operations
        System.out.println
        (
            IntStream
            .range(1, 6)
            .sum()
        );

        //Sum the squares of the first five positive integers
        //The old way, using an accumulator and a for-loop
        sum = 0;
        for (int i = 1; i <= 5; i++)
        {
            sum = sum + i * i;
        }
        System.out.println(sum);

        //The new way, using a pipeline with one intermediate operation
        System.out.println
        (
            IntStream
            .range(1, 6)
            .map(n -> n * n)
            .sum()
        );

        //Sum the squares of odd values among first five positive integers
        //The old way, using an accumulator, an if-statement, and a for-loop
        sum = 0;
        for (int i = 1; i <= 5; i++)
        {
            if (i % 2 != 0)
            {
                sum = sum + i * i;
            }
        }
        System.out.println(sum);

        //The new way, using a pipeline with two intermediate operations
        System.out.println
        (
            IntStream
            .range(1, 6)
            .filter(n -> n % 2 != 0)
            .map(n -> n * n)
            .sum()
        );
    }
}
/*  Output:
    15
    15
    55
    55
    35
    35
*/
