What is Stream API ?

What is Stream API ?

Motivation

this is asked in almost all the interviews so lets get right into it and demystify it.

Stream API in java

Stream API is basically used with the collections of objects, it will not modify the original data, and we can pipeline together multiple methods using stream,

Examples

  1. map
  2. filter
  3. collect
  4. reduce
  5. forEach

Map

  • with the map we can do some operation on each of the element in the list, we can write a mehtod to add one to all the elements

filter

  • Lets say we wants to filter the list elements by some conditions we can do it using filter, we can filter lets say if the number is >0 only

Reduce

it will reduce the complete list to a single elemtn, lets say i wanted to add all the elemtns

collect.

It is a terminal method it can be used to collect the list elements into a list

forEach

this will be used on each element of the list ,

Lets see examples of each of the method


lass App {
    public static void main(String[] args) {
        System.out.println("hellow world");


        List<Integer> number=Arrays.asList(1,2,3,4,5);


        List<Integer> finalList= number.stream().map(x->x+10).collect(Collectors.toList());

        System.out.println(finalList);


       List<Integer> greaterThan3= number.stream().filter(x->x>3).collect(Collectors.toList());

       System.out.println(greaterThan3);


       int reduced=number.stream().map(x->x+20).reduce(0,(ans,i)->ans+i);


       System.out.println(reduced);

    }
}