Source of TestIntStream.java


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

  7: import java.util.stream.IntStream;

  9: public class TestIntStream
 10: {
 11:     public static void main(String[] args)
 12:     {
 13:         //Sum the first five positive integers
 14:         //The old way, using an accumulator and a for-loop
 15:         int sum = 0;
 16:         for (int i = 1; i <= 5; i++)
 17:         {
 18:             sum = sum + i;
 19:         }
 20:         System.out.println(sum);

 22:         //The new way, using a pipeline with zero intermediate operations
 23:         System.out.println
 24:         (
 25:             IntStream
 26:             .range(1, 6)
 27:             .sum()
 28:         );

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

 39:         //The new way, using a pipeline with one intermediate operation
 40:         System.out.println
 41:         (
 42:             IntStream
 43:             .range(1, 6)
 44:             .map(n -> n * n)
 45:             .sum()
 46:         );

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

 60:         //The new way, using a pipeline with two intermediate operations
 61:         System.out.println
 62:         (
 63:             IntStream
 64:             .range(1, 6)
 65:             .filter(n -> n % 2 != 0)
 66:             .map(n -> n * n)
 67:             .sum()
 68:         );
 69:     }
 70: }
 71: /*  Output:
 72:     15
 73:     15
 74:     55
 75:     55
 76:     35
 77:     35
 78: */