Monday 4 November 2019

Stream API

Stream : The Java Stream API provides a more functional programming approach to iterating and processing elements of e.g. a collection and coming for java8

Stream in java can be defined as a sequence of elements from source that supports aggregate operations or bulk operations on them. The source here refers to a Collection or Arrays.

Note: If we want to process object from the collection should be use Stream.
  1. Stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
  2. Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  3. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
  4. Stream coming from java.util package.
Characteristics of Stream:-
  1. Not a data structure.
  2. Designed for lambdas.
  3. Do not support indexed access.
  4.  Can easily be outputted as array or list.
  5. Lazy access supported.
  6. Parallelizable.
Example 1:

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(10);
al.add(5);
al.add(15);
al.add(25);
 System.out.println("List Provied insertion order :"+al);

Output: [0,10,20,5,15,25]

Example 2 : Without Streams(Util 1.7 version)

List<Integer> l1 = new ArrayList<Integer>();
  for(Integer I1 L l1)
   {
      if(I1 % 2 == 0)
       {
          l1.add(I1);
        }
     }
 System.out.println("List Provied Even order :"+l1);

Example 3 : How to get even number in list using Stream(From 1.8 version)

             List<Integer> l1 = new ArrayList<Integer>();
              List<Integer> l=al.stream().filter(I -> I%2==0).collect(Collectors.toList());
              System.out.println("Even number is: "+l);
Output: [0,10,20]

 Example 4:    How to get multiple(*)2 value in given above list.

                    List<Integer> l1 = new ArrayList<Integer>();
                    List<Integer>  l1= al.stream().map(I -> I*2).collect(Collectors.toList());
                    System.out.println(l1);
Output: [0, 20, 10, 30, 50]

           Stream s =c.stream();
         
           Stream =>It is a functional interface coming from java.util.stream package.
           stream() =>stream() method coming from collection interface as a default method.

Java Stream intermediate operations

There are two way
  1.  Using Filter mechanism
  2.  Using Map mechanism
Filter mechanism: when filter the even number from collection to use Filter mechanism.
   Please go through example 3.

Map mechanism : When double the number then use map mechanism.
   Please go through example 4.

Filter : 

If we want to filter elements from the collection base on some boolean condation then we should go for filtering.
We can configure filter by using filter() method of Stream interface.

  Syntex:
                    public Stream filter(Predicate<T> t)

   Predicate: It is return boolean  value function or Lambda Expression.
 
    Example:  Stream s1 = c.stream().filter(i->i%2==0);

Mapping:

If we want to create a separate new object from every object present in the Collection based on some function then we should go for mapping mechanism.

We can implement mapping by using map() method of Stream interface.

Syntex.

           public Stream map(function<T , R>  f)

Example:   Stream s1 = c.stream().map(i->i*2);

Method of Stream:

     Intermediate Operations : Intermediate operations return the stream itself .
  1. filter()
  2. map()
  3. flatMap()
  4. distinct()
  5. sorted()
  6. peek()
  7. limit()
  8. skip()
    Terminal Operations : Terminal operations return a result of a certain type instead of again a Stream.
  1. collect()
  2. count()
  3. sorted()
  4. Min()
  5. Max()
  6. forEach()
  7. forEachOrdered()
  8. toArray()
  9. Stream.of()
  10. generate()
  11. iterate()
  12. match()
  13. anyMatch()
  14. allMatch()
  15. noneMatch()
  16. reduce()
  17. findFirst()
  18. findAny()
Example 5 : How to use filter() method in Stream.
Output:
List provide insertion order :[0, 10, 5, 15, 25]
Even number is: [0, 10]

Example 6 : How to use map() method in Stream.

Output:
List provide insertion order :[0, 10, 5, 15, 25]
[0, 20, 10, 30, 50]

Java Stream filterMap:
  1. filterMap() : Stream flatMap() method which is used to flatten a stream of collections to a stream of elements combined from all collections.
  2. flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream.
  3. It is an intermediate operation and return another stream as method output return value.
  4. Returns a stream consisting of the results of replacing each element of the given stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
  5. The function used for transformation in flatMap() is a stateless function and returns only a stream of new values.
  6. Each mapped stream is closed after its contents have been placed into new stream.
  7. flatMap() operation flattens the stream; opposite to map() operation which does not apply flattening.
Example 7 :

Share this

0 Comment to "Stream API"

Post a Comment