| Home | Thoughts

Title

November 30, 2020

JAVA STREAMS:

Lets Move away from imperative programming & move towards Functional Programming.

We don't need to write down every step of the code. That my freing it is pretty old school.

It can lead to errors, & bugs. Yes we can praise our founding fathers and learn from the basics, but we need to be progressives as well.

Imperative programming can be clunky, fattened with a bunch of boiler plate code.

Java Streams can be described as a pipeline of various operations that can be applied to process a collection of elements.

Java streams don't execute anything, we first declare what our pipeline will be doing and will be waiting to executed by a terminal operation.

Java Streams have 3 main phases:

Split : This is where the data is collected, and we convert it to a stream in order to be processed. This is called the stream source

Apply : Every operation in the pipeline is applied to each element in the sequence.

Combine : To finalize the stream we need to complete it with a terminal operation (materialized) Some of the Data Structure conversions are

  
    public class Car(int id, String type, int numberOFSeats){
    }

    car car1 = new Car(1, "SUV", 4);
    Car car2 = new Car(2, "Minivan", 7);


    List:
    Simplest Use case is converting a stream into a list.

    List cars = Stream
    .of(car1,car2);
    .collect(Collectors.toList());

  

Lambda Expressions is a short block of code that takes in parameters and returns a value. Similar to a method, but they dont need a name and they can be implemented right out the box.

MAP:

Converting a stream to a map. Call collect method, and pass in as a arguement Collectors.toMap The toMap() method accepts two arguements

1st will be a lambda that returns the key of the map 2nd a lambda will be the value for that key in the map

  
    Map carsMap = Stream
      .of(car1,car2)
      .collect(Collectosrs.toMap(car -> car.id, car -> car));