Source of TestSimplePipeline1.java


  1: //TestSimplePipeline1.java
  2: //Illustrates the idea of a Java "pipeline":
  3: //source --> (zero or more) intermediate operations --> terminal operation
  4: //This is a very powerful concept that is now available to
  5: //us in Java 8 and and later Java versions.

  7: import java.util.ArrayList;

  9: public class TestSimplePipeline1
 10: {
 11:     public static void main(String[] args)
 12:     {
 13:         ArrayList<Double> nums = new ArrayList<>();
 14:         nums.add(3.5);
 15:         nums.add(56.3);
 16:         nums.add(81.1);
 17:         nums.add(4.8);

 19:         nums.stream()
 20:         .filter((Double val) -> val > 50) //The type of val is explicit.
 21:         .forEach((Double val) -> System.out.println(val));
 22:         //Here forEach() is using a lambda function as its parameter.

 24:         System.out.println();

 26:         //The following statement is equivalent to the above statement.
 27:         nums.stream()
 28:         .filter(val -> val > 50) //The type of val is "inferred".
 29:         .forEach(System.out::println);
 30:         //Here forEach() is using a "method reference" as its parameter.

 32:         System.out.println();

 34:         //Here we have no intermediate operations:
 35:         System.out.println(nums.stream().count());
 36:     }
 37: }
 38: /*  Output:
 39:     56.3
 40:     81.1

 42:     56.3
 43:     81.1

 45:     4
 46: */