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 :

Supplier Interface



Supplier : Supplier is a functional Interface is coming form java.util.funcation package. Which has been introduces in java 8 to implement functional programming in java.

                                         interface Supplier<T>{
                                                public T get();
                                          }
Note: T is type of results Supplied by the Supplier.
  1. Supplier does not take any argument but produces a value of type T.
  2. Supplier functional Interface contains only one default method is call get().
  3. get() method is abstract method so under supplier interface.
  4. Supplier functional interface don't contain any static and default method.
Example 1: How to get System date using Supplier functional interface.

 Output: Mon Nov 04 14:52:32 IST 2019

Example 2: How to generate random name using supplier functional interface.

Output:-
Baby
Pinny
Maya

Example 3: How to generate random 6-digit OTP using Supplier Functional Interface.
Output:
515121
550490
650770
609529

Example 4 : How to get random password using Supplier functional interface.


Output:-
A9A2A5A0
A9A8A2A2
A0A5A2A2
A3A7A6A8

Comparison Table of Predicate, Function, Consumer and Supplier Functional Interface.


Wednesday 30 October 2019

Consumer Interface

The Consumer Interface is a part of the java.util.function package which has been introduced in Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. However these kind of functions don’t return any value.
  1. Consumer Functional Interface contains one abstract method accept. 
  2. Sometimes our requirment is we have to provide some input value, perform certain operation.
  3. But not required to return anything,then we should go for Consumer.i.e Consumer can be used to consume object and perform certain operation.
  4. Consumer interface contain one abstract method is accept().
  5. Consumer Functional Interface contains default method andThen().
Syntax:
       
              interface Consumer<T>   
              {
                         public void accept(T t);   
              }

             T-the type of the input to the operation.
             t- the input argument.
           
Example:1. How to display input value using Consumer Functional interface.


Output:
Hello
Hello Sudhir

Saturday 26 October 2019

Function Interface

  1. Function interface is a part of the java.util.function package which has been introduced in java 8.
  2. Functions are exactly same as predicates except that functions can return any type of result but function should (can) return only one value and that value can be any type as per our requirement. 
  3. Function interface present in Java.util.function package. 
  4. Functional interface contains only one method i.e., apply().
   Syntex:
                     interface function(T,R) {   
                                  public R apply(T t); 
                        }
                  T: 
denotes the type of the input argument.
                  R: denotes the return type of the function.

  Example 1:Write a function to find length of given input string
Output:

6

11

25

100

 Note: Function is a functional interface and hence it can refer lambda expression.

Differences between predicate and function 
     Predicate:
  1. To implement conditional checks We should go for predicate .
  2.  Predicate can take one type Parameter which represents Input argument type. Predicate<T> 
  3. Predicate interface defines only one method called test().
  4. public boolean test(T t).
  5. Predicate can return only boolean value. 
  Function:
  1. To perform certain operation And to return some result we Should go for function.
  2. Function can take 2 type Parameters. First one represent Input argument type and Second one represent return Type.  Function<T,R>
  3. Function interface defines only one Method called apply(). 
  4. public  R  apply(T t) .
  5. Function can return any type of value.
Note: Predicate is a boolean valued function and(), or(), negate() are default methods present inside Predicate interface. 

Example 2.1:  To remove spaces present in the given String by using Function .
                2.2:   How to find Number of spaces present in the given String by using Function.


Output:-
HelloSudhirhowareyou
4

Example 3: To find Student Grade by using Function

Friday 25 October 2019

Predicate Interface


  1. Predicate is a mathematics term to introduce java 8 as a functional interface. version (i.e.,Predicate<T>). 
  2. Predicate is  a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
  3. A predicate is a function with a single argument and returns boolean value. 
  4. Predicate interface present in Java.util.function package.
  5. It’s a functional interface and it contains only one method i.e., test()

      Syntex.
                           interface Predicate<T> {   
                                        public boolean test(T t);                
                             }
         
     Method Detail
                 public boolean test(T t); 

    Parameters
                  T - the type of arguments to the predicate                  
                  t - the input argument.
    Returns

                 True if the input argument matches the predicate, otherwise false.


         As predicate is a functional interface and hence it can refers lambda expression. 

   Example: 1. 
      Write a predicate to check whether the given integer is greater than 10 or not. 

                       public boolean test(Integer I) { 
                             if (I >20) { 
                                ⇩⇩  return true; 
                              }
                              else { 
                                   return false; 
                              }
                            }
                                   
                                     
                        (Integer I) -> {
                                      if(I > 20 )
                                          return true;
                                      else 
                                          return false;
                                       }

                                      
                                 I ->(I > 20);
                                     
                                      
                            predicate<Integer> p = I (I >20); 
                            System.out.println (p.test(100)); true 
                            System.out.println (p.test(17)); false 

Example 1:
                     class Test { 
                           public static void main(String[] args) {   
                                  predicate<Integer> p = I  (i>10); 
                                   System.out.println(p.test(100)); 
                                   System.out.println(p.test(17)); 
                                   System.out.println(p.test(true)); //Compile time error                                    }
                               }

Example 2.Write a predicate to check the length of given string is greater than 5 or not.
         

     
 Example 3: Write a predicate to check whether the given collection is empty or not. 

        


 Predicate Joining:-

  It’s possible to join predicates into a single predicate by using the following methods.
  1. and()  
  2. or()  
  3. negate()
 these are exactly same as logical AND ,OR complement operators.

Example 4: How to use Predicate in Functional interface


Output:-

The Numbers Greater Than 10:
15
20
25
30
The Even number are :
0
10
20
30
The number not Greater then 10:
0
5
10
The number Greater then 10  and Even are:
20
30
The number Greater then or Even are
0
10
15
20
25
30


 Example 4: To Display names starts with 'K' by using Predicate.


Output:-

The name Start with K are :
Kareena
Kajal
Kareena
Katrina

Example 5: To remove null values and empty strings from the given list.



Output:- The List of valid Name : [Sudhir, Ram, Kajal, Monika, Kareena, Katrina]


Example 6: User Authentication by using Predicate


Output:-
Enter the Username :
Sudhir
Enter the Password :
sudhir

Valid user and can avail all services

Example 7: To check whether SoftwareEngineer is allowed into pub or not by using Predicate


Output:-
The Allowed number into Pub are :
Sudhir
Sudhir
Asha
Aarti

Example 8: Employee Management Application.

Output:-
Manager Information :
[Rakest,Developer,40000.00,Bangalore]
**************************************************
Bangalore Employees Information:
[Sudhir,Team Lead,30000.00,Bangalore]
[Aarti,Test Engineer,30000.00,Bangalore]
[Rakest,Developer,40000.00,Bangalore]
**************************************************
[[Sudhir,Team Lead,30000.00,Bangalore], [Aarti,Test Engineer,30000.00,Bangalore], [Rakest,Developer,40000.00,Bangalore], [Manish,Software Engineer,20000.00,Hyderabad], [Neha,Operation Manager,50000.00,Hyderabad], [Ram,ECO,300000.00,Patna]]



Thursday 24 October 2019

Static methods


  1. Java interface static method is similar to default method except that we can’t override them in the implementation classes.
  2. They are part of interface, we can’t use it for implementation class objects.
  3.  It helps in providing security by not allowing implementation classes to override them.
  4.  Interface static methods by-default not available to the implementation classes hence by using             implementation class reference we can’t call interface static  Method.
  5. We should call interface static methods by using interface name.
            Example 1.

                   interface Static
                    {  
                              public static void sum(int a, int b)
 {  
                                         System.out.println("The Sum:"+(a+b));  
                              }  
 }  
                   class Test implements Static{  
                             public static void main(String[] args)
{   
                                           Test t = new Test();                     
t.sum(10, 20); //Compile Time Error                     
                                          Test.sum(10, 20); //Compile Time Error
                                          Static.sum(10, 20);       
                              }
                      }

            Example 2.
               interface Static{       
                       public static void m1() {} }
               class Test implements Static{  
                     public static void m1() {}  }
               It’s valid but not overriding

             Example 3.
                   interface Static
                  {  
                      public static void m1() {}  
                  }  
                  class Test implements Static
                 {  
                     public void m1() {}  
                 }    
                             This’s valid but not overriding

            Example 4.
           class P{  
                          private void m1() {}  
                      }  
            class C extends P {  
                    public void m1() {}  
                     }  
                              This’s valid but not overriding

               From 1.8 version onwards we can write main() method inside interface and hence  we can run             interface directly from the command prompt.


              Example : 5
 interface Static{  
      public static void main(String[] args) {  
                System.out.println("Interface Main Method");    
       }  
 }

Example :6.  How to call static method in Functional Interface using java 8


Output:- Static Method











Anonymous Inner Class in Funcational Interface

Anonymous Inner Class

Anonymous inner class is without having any name such type of class is called anonymous inner class.

Example 1.

Runnable    r = new Runnable (){
              public void run () {
}
}

Note: -
  1. Anonymous inner class that extends concreate class.
  2. Anonymous inner class that extends Abstract class.
  3. We can declare instance variable with in the anonymous inner class.
  4. Anonymous inner class is not equal to Lambda expression.

Note:- this.x always refers to inner variable in anonymous inner class.

interface InterfB{
     
      public void m1();
}
public class TestAnonymous {

      int x=10;
      public void m2(){
            InterfB interfB = new InterfB() {
                 
                   int x=20;
                 
                  @Override
                  public void m1() {
                       
                        System.out.println(this.x);
                  }
            };
            interfB.m1();
      }
     
      public static void main(String[] args) {
           
            TestAnonymous testAnonymous = new TestAnonymous();
            testAnonymous.m2();
      }
}
Result:- 20

Note:- this.x lambda expression refers outer variable only.

Example 2.

interface interfC{
      public void m1();
}
public class TestwithLambda {

      int x=10;
      public void m2(){
            interfC i =  ()->{
                  int x=20;        
                        System.out.println(this.x);  
                 
            };
            i.m1();    
      }
      public static void main(String[] args) {
            TestwithLambda lambda = new  TestwithLambda();
            lambda.m2();
      }
}

Result:-10

Example 3. With Anonymous function using Thread.

public class ThreadWithAnonymousDemo {


public static void main(String[] args) {

Thread t= new Thread(()->System.out.println("Child Thread"));
t.start();
for(int i=0; i<10; i++){
System.out.println("Main Thread");
}
}
}

Example 4. With Lambda Expression.

public class ThreadWithAnonymousDemoUsingLambda {

public static void main(String[] args) {

Runnable r = new Runnable(){

@Override
public void run() {
for(int i=0; i<10; i++){
System.out.println("Child Thread");
}

}

};

Thread t = new Thread(r);
}
}

Example : 5. How to use annonymous funcation in Lambda Expression.


Difference between Anonymous inner class and Lambda Expression

Anonymous inner Class
  1.   It is a class without name.
  2.   Anonymous inner class can extends Abstract class and Concrete classes.
  3.   Anonymous inner class can implements as interface that contains any number of abstract methods;
  4.   Inside Anonymous inner class We can declare instance variable.
  5.   Anonymous inner class can be instantated.
Lambda Expression
  1.     It is function without name (Anonymous function).
  2.     Lambda Expression can’t extends Abstract class and Concrete classes.
  3.     Lambda Expression can implement as interface which contains single abstract method(Functional        Interface) .
  4.     Inside Lambda Expression we can declare instance variable what ever variable declared are         consider as local variables.
  5.      Lambda Expression cannot be instantiated.