Saturday, June 17, 2017

Java 8 : Streams

Its an layer / wrapper around collection, that enables declarative data processing like SQL. They can be sourced from Collections , Arrays . I/O.

Some characteristics include
  1. Support pipeline operations : output of a stream operation can be another stream
  2. Auto Iterations
  3. Lazy Evaluation 
  4. Automatic parallelization

Streams have 2 kinds of operations to it
  1. Intermediate : they return one more stream
    • filter
    • map
    • sorted
  2. Terminal : they return a void or a non-stream
    • forEach
    • ifPresent
Most Stream operations accept lambda specifying exact behavior of operation.

With these inputs its easy to see how these code snippets would work
public static void method1() {
   Arrays.asList("alpha1", "alpha2", "alpha3")

Another Example

public static void method2() {
  List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
  List<String> filtered = -> !string.isEmpty()).collect(Collectors.toList());

Streams can be of two types
  1. Sequential
  2. Parallel : can be executed parallely without need to write MultiThreaded code.

No comments: