Java Streams

What is a streams?

  • Stream is just an Abstraction.
  • This abstraction focuses on all instead of little parts. (We can write the code instead of focusing on how to assemble the little parts).
  • Imperative to functional programming.(Imperative means doing some task require assigning looping and many more things to under stand what the program does to functional programming in which it looks like we are just reading sentences)
  • Streams mostly used with Collections.

How to use java streams?

  1. Find a concrete class. example (Arrays, List, Map, Set)
  2. call the .stream() method on that object of the above class
    • The beauty of streams is that we can concat streams
    • Return type of a stream can also be a stream which we will chain together
    • A stream can a filter, limit, map, reduce etc
    • Streams a basically abstraction, we don’t tell stream how to do but only what to do thus we call streams as abstraction
  3. Return a concrete class back from stream.
    • This return can be a list, int, object, optional, string etc
    • Example methods that return a concrete class : sum(), collect(Collectors.toList()),average, collect(Collectors.groupBy())

Example :

 MockData.getPeople()
      .stream() //Converting concrete -> Abstraction 
      .filter(p -> p.getAge() <= 18) //Filter stream
      .limit(10) //Limit Stream
      .collect(Collectors.toList()) //Convert abstraction -> concreate
      .forEach(System.out::println); //printing the list

Leave a Comment