Tuesday 22 August 2017

Java 8 New Feature

Java 8 new Feature 
·         forEach() method in Iterable interface.
·         forEachOrdered() method for Java Stream
·         Java Time API.
·         default and static methods in Interfaces.
·         Collection API improvements.
·         Concurrency API improvements.
·         Functional Interfaces and Lambda Expressions.
·         Java Stream API for Bulk Data Operations on Collections.
·         Java IO improvements.
·         optional class
·         final class StringJoiner
·         java optional classes and optional methods




1> forEach() -

In Java 8 a new method forEach() is added to iterate the elements. It is defined in Iterable and Stream interfaces. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach() method to iterate elements. You can use lambda expression as an argument.Because this method can take single parameter which is a functional interface..

forEach() method signature in Iterable Interface

default void forEach(Consumer<super C>action)

Example1 :-forEach() using Lamda Expression
1.    import java.util.ArrayList;  
2.    import java.util.List;  
3.    public class ForEachExample001 {  
4        public static void main(String[] args) {  
5           List<String> toysList = new ArrayList<String>();  
6          toysList.add("Football");  
7           toysList.add("Ball");  
8           toysList.add("Doll");  
9           toysList.add("Car");  
1         System.out.println("*******Iterating by passing lambda expression********");  
1         toysList.forEach(toys -> System.out.println(toys));  
    
1    }  
1 }  

output :

*******Iterating by passing lambda expression********
Football
Ball
Doll
Car


Example2 :-forEach() using functional interface 

import  java.util.ArrayList;
import  java.util.Iterator;
import  java.util.List;
import  java.util.function.Consumer;
import  java.lang.Integer;

public class ForEachExample002 {

 public static void main(String[] args) {
 
  //creating sample Collection
 
           List<Integer> list0 = new ArrayList<Integer>();
  for(int a=0; a<10; a++) list0.add(a);
 
  //traversing using Iterator
  Iterator<Integer> it = list0.iterator();
  while(it.hasNext()){
   Integer n = it.next();
   System.out.println("Iterator Value::"+n);
  }

          //traversing through forEach method of Iterable with anonymous class

 list0.forEach(new Consumer<Integer>() {

   public void accept(Integer t) {
    System.out.println("forEach anonymous class Value::"+t);
   }

  });
 
  //traversing with Consumer interface implementation
 
        MyConsumer action = new MyConsumer();
  list0.forEach(action);
 
 }
}

 //Consumer implementation that can be reused
   class MyConsumer implements Consumer<Integer>{

 public void accept(Integer t) {
  System.out.println("Consumer Impl Value::"+t);
 }


}

output :
Iterator Value::0
Iterator Value::1
Iterator Value::2
Iterator Value::3
Iterator Value::4
Iterator Value::5
Iterator Value::6
Iterator Value::7
Iterator Value::8
Iterator Value::9
forEach anonymous class Value::0
forEach anonymous class Value::1
forEach anonymous class Value::2
forEach anonymous class Value::3
forEach anonymous class Value::4
forEach anonymous class Value::5
forEach anonymous class Value::6
forEach anonymous class Value::7
forEach anonymous class Value::8
forEach anonymous class Value::9
Consumer Impl Value : 0
Consumer Impl Value : 1
Consumer Impl Value : 2
Consumer Impl Value : 3
Consumer Impl Value : 4
Consumer Impl Value : 5
Consumer Impl Value : 6
Consumer Impl Value : 7
Consumer Impl Value : 8
Consumer Impl Value : 9

Example3 :-forEach() by passing method reference 

import java.util.ArrayList;  
import java.util.List;  
public class ForEachExample001 {  
    public static void main(String[] args) {  
        List<String> toysList = new ArrayList<String>();  
        
        toysList.add("Football");  
        
        toysList.add("Ball");  
        
        toysList.add("Doll");  

        toysList.add("Car");  

        System.out.println("*******Iterating by passing method reference********");  

        toysList.forEach(System.out::println);  
          
    }  
}  

output :

*******Iterating by passing method reference********
Football
Ball
Doll
Car


2> forEachOrdered() - method for Java Stream iterator 

It is used to iterate elements in the order specified by the stream.




forEachOrdered() method signature:-



 void forEachOrdered(Consumer<super C>action)

Example :-forEachOrdered()

import java.util.ArrayList;
import java.util.List;
public class ForEachOrderedExample00 {
    
        public static void main(String[] args) {
         
     List<String> toyslist = new ArrayList<String>();
       
        toyslist.add("Football");
     
        toyslist.add("Car");

        toyslist.add("Bus");

        toyslist.add("Doll");

        System.out.println("*****Iterating by passing lambda expression******");

        toyslist.stream().forEachOrdered(toys -> System.out.println(toys));

        System.out.println("******Iterating by passing method reference*****");

        toyslist.stream().forEachOrdered(System.out::println);    
        }

}

output :

*****Iterating by passing lambda expression******
Football
Car
Bus
Doll
******Iterating by passing method reference*****
Football
Car
Bus
Doll



3> default and static method in Interface :-



Before Java 8 there no method body in interface, but know from java 8 there is a two different type of methods with body are static and default methods, to declare default and static method with there body inside interface.

forEach():-signature is- 

default void forEach(Consumer<super C>action){
       Objects.requireNonNull(action);
for(C c:this){
action.accept(c);
}
}

which is declare inside iterable interface.
The concept of default method is used to define a method with default implementation. You can override default method also to provide more specific implementation for the method.  
Static method is used to defined utility methods. 

Multiple Inheritance is not possible in java classes because it lead to big problems. But it handled in interface.
know interfaces are similar to abstract classes.But for this concept we must provide implementation logic in implementing class otherwise compiler will throw exception.

Example1 :-default method inside interface 
interface S1{  
   
 // Default method   
    default void s1(){  
      
  System.out.println("Hello, it is default method");  
    }  
   // Abstract method    
void s2(String msg);  
}  

public class DefaultMethods implements S1{  
    
//implementing abstract method 

public void s2(String msg){         
   System.out.println(msg);  
    }  

    public static void main(String[] args) {  
      
  DefaultMethods dem = new DefaultMethods();  

//calling default method      
   dem.s1();  
 //calling abstract method     
  dem.s2("Java 8 Having New Features");  

  
    }  
}  

output :


Hello, it is default method
Java 8 Having New Features


Example2 :-static method inside interface 
interface I2{    
    // default method    
    default void m1(){    
        System.out.println("Hello, it is default method");    
    }    
    // Abstract method    
    void m2(String str);    
    // static method    
    static void m3(String str){    
        System.out.println(str);    
    }    
}    
public class DefaultMethods00 implements I2{ 

 // implementing abstract method 
    public void m2(String str){        
        System.out.println(str);    
    }    
    public static void main(String[] args) {    
        DefaultMethods00 dem0 = new DefaultMethods00(); 
        
        // calling default method    
        dem0.m1(); 
        
     // calling abstract method  
        dem0.m2("Java 8 having New Features");
        
     // calling static method    
        I2.m3("See Carefully....");   
    }
    
}    


output :


Hello, it is default method
Java 8 having New Features
See Carefully....


Example3 :-static and default both methods inside interface

Interface01:-

package com.DefaultAndStaticMethods;

@FunctionalInterface
public interface Interface01 {

 void m1(String str);

 default void logging(String str){
  System.out.println("I1 logging::"+str);
 }

 static void printing(String str){
  System.out.println("Printing "+str);
 }

 //trying to override Object method gives compile time error as
 //"A default method cannot override a method from java.lang.Object"

// default String toString(){
//  return "i1";
// }

}

Interface02 :-

package com.DefaultAndStaticMethods;

@FunctionalInterface
public interface Interface02 {

 void m2();

 default void logging(String str){
  System.out.println("I2 logging::"+str);
 }

}


MyClassTest :-

package com.DefaultAndStaticMethods;

public class MyClassTest implements Interface01, Interface02 {

 @Override
 public void m2() {
 }

 @Override
 public void m1(String str) {
 }

 //MyClassTest won't compile without having it's own logging() implementation
 @Override
 public void logging(String str){
  System.out.println("MyClassTest logging::"+str);
  Interface01.printing("abc");
 }

}


Important points about java interface static method:
1.    Java interface static method is part of interface, we can’t use it for implementation class objects.
2.    Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.
3.    Java interface static method helps us in providing security by not allowing implementation classes to override them.
4.    We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.

5.    We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use.



> Abstract Class vs Interface in java 8

Due to addition of two methods default and static methods inside the interface.Know we can say An interface and an abstract class is almost similar except that you can create constructor in the abstract class whereas you can't do this in interface.

Example :- 

abstract class AbstractClass{

 // constructor
    public AbstractClass() {        
        System.out.println("You can create constructor in abstract class");  
    }

 // abstract method
    abstract int add(int a, int b);

    // non-abstract method
    int sub(int a, int b){    
        return a-b;  
    }

    // static method
    static int multiply(int a, int b){  
        return a*b;  
    }  
}  
public class AbstractTest extends AbstractClass{

   // implementing abstract method
    public int add(int a, int b){        
        return a+b;  
    }  
    public static void main(String[] args) {  
        AbstractTest a = new AbstractTest();
     
     // calling abstract method
        int result1 = a.add(20, 18);
     
     // calling non-abstract method
        int result2 = a.sub(20, 18);  
     
     // calling static method
        int result3 = AbstractClass.multiply(20, 18);  
     
        System.out.println("Addition: "+result1);  
        System.out.println("Substraction: "+result2);  
        System.out.println("Multiplication: "+result3);  
    }  
}

output :

You can create constructor in abstract class
Addition: 38
Substraction: 2
Multiplication: 360


4> final class StringJoiner

In Java 8 new final class StringJoiner added in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.

There is a big difference between StingBuilder And StringJoiner. StringBuilder provides append() method but StringJoiner provides join().

The append() method doesn't know that you don't need to add delimiter after the last element but join() does. So you don't need to handle either first or last element in joining loop anymore.
And StringJoiner is used for Java Stream.


Example1 :-joining of java stream by comma
StringJoiner joiner=new StringJoiner(",");
joiner.join("Sony");
String joined=joiner.toString();
Public StringJoiner(CharSequence delimiter)
Public StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix)
Public StringJoiner add(CharSequence newElement)


joiner.join("Samsung");
joiner.join("Nokia");
joiner.join("Lenovo");


StringJoiner Constructor :-



StringJoiner methods :-

Public StringJoiner merge(CharSequence newElement)
Public int length();
Public StringJoiner setEmptyValue(charSequence emptyValue)

Example2 :-joining of java stream by comma

import java.util.StringJoiner;  
public class StringJoinerExample {  
    public static void main(String[] args) {  

// passing comma(,) as delimiter
        StringJoiner joinNames = new StringJoiner(",");    
          
        // Adding values to StringJoiner  
        joinNames.add("Rahul");  
        joinNames.add("Raju");  
        joinNames.add("Peter");  
        joinNames.add("Raheem");  
                  
        System.out.println(joinNames);  
    }  

}  


output : 

Rahul,Raju,Peter,Raheem

Example3 :-adding prefix and suffix

import java.util.StringJoiner;  
public class StringJoinerExample {  
    public static void main(String[] args) {  

 // passing comma(,) and square-brackets as delimiter   
          
        StringJoiner joinNames = new StringJoiner(",", "[", "]");  
      
  // Adding values to StringJoiner  
        joinNames.add("Rahul");  
        joinNames.add("Raju");  
        joinNames.add("Peter");  
        joinNames.add("Raheem");  
                  
        System.out.println(joinNames);  
    }  

}  

output :

Rahul,Raju,Peter,Raheem


Example3 :-Merge two StringJoiner 


import java.util.StringJoiner;  
public class StringJoinerExample {  
    public static void main(String[] args) {  
  

// passing comma(,) and square-brackets as delimiter  
        StringJoiner joinNames = new StringJoiner(",""[""]");    
          
        // Adding values to StringJoiner  
        joinNames.add("Rahul");  
        joinNames.add("Raju");  
  
        // Creating StringJoiner with :(colon) delimiter  
 // passing colon(:) and square-brackets as delimiter   
        StringJoiner joinNames2 = new StringJoiner(":""[""]"); 
       
 // Adding values to StringJoiner  
        joinNames2.add("Peter");  
        joinNames2.add("Raheem");  
  
        // Merging two StringJoiner  
        StringJoiner merge = joinNames.merge(joinNames2);   
        System.out.println(merge);  
    }  

output :

[Rahul,Raju,Peter:Raheem]


Example3 :-StringJoiner methods

import java.util.StringJoiner;
public class StringJoinerExample {
    public static void main(String[] args) {
    
     // passing comma(,) as delimiter  
        StringJoiner joinNames = new StringJoiner(",");
       
        // Prints nothing because it is empty  
        System.out.println(joinNames);
       
        // We can set default empty value.  
        joinNames.setEmptyValue("It is empty");
        System.out.println(joinNames);
       
       
        // Adding values to StringJoiner  
        joinNames.add("Rahul");
        joinNames.add("Raju");
        System.out.println(joinNames);
       
        // Returns length of StringJoiner
        int length = joinNames.length();
        System.out.println("Length: "+length);
       
        // Returns StringJoiner as String type   
        String str = joinNames.toString();
        System.out.println(str);
       
        // Now, we can apply String methods on it  
        char ch = str.charAt(3);
        System.out.println("Character at index 3: "+ch);
       
        // Adding one more element   
        joinNames.add("Sorabh");
        System.out.println(joinNames);
       
        // Returns length  
        int newLength = joinNames.length();
        System.out.println("New Length: "+newLength);
    }

}


output :

It is empty
Rahul,Raju
Length: 10
Rahul,Raju
Character at index 3: u
Rahul,Raju,Sorabh
New Length: 17


5> Optional class :-

In Java 8 there is new class introduces know as optional class.It is a public final class used to deal with NullPointerException in java applications.But for using this class need to import java.util package. It provides method to check the presence of values of particular variables.

Optional is a container of object which is used to contains "not-null object".Optional object is used to present null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

Optional class Methods :-

public static <T> Optional<T> empty()

public static <T> Optional<T> of(T value)

public static <T> Optional<T> ofNullable(T value)

public T get()

public boolean isPresent()

public void ifPresent(Consumer<? super T> consumer)

public Optional<T> filter(Predicate<? super T> predicate)

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper)

public T orElse(T other)

public T orElseGet(Supplier<? extends T> other)

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable

public boolean equals(Object obj)

public int hashCode()

public String toString()


Example1 :-Java program without optional class


public class OptionalExample1 {  
    public static void main(String[] args) {  
        String[] str = new String[10];  
        String lowercaseString = str[5].toLowerCase();  
        System.out.print(lowercaseString);  
    }  

}  

output :

Exception in thread "main" java.lang.NullPointerException
 at OptionalExample.main(OptionalExample.java:5)

Example2 :-Java program with optional class; if value is not present

import java.util.Optional;

public class OptionalExample2 {

 public static void main(String[] args) {

    String[] str = new String[10];
   
  Optional<String> checkNull = Optional.ofNullable(str[5]);

 // check for value is present or not
        if(checkNull.isPresent()){
       
  String lowercaseString = str[5].toLowerCase();
       
  System.out.print(lowercaseString);
     
 }else
            System.out.println("string value is not present");
    }
}

output :

string value is not present

Example3 :-Java program with optional class; if value is present
import java.util.Optional;

public class OptionalExample3{

 public static void main(String[] args) {
     
  String[] str = new String[10];
   
        // Setting value for 5th index
        str[5] = "JAVA OPTIONAL CLASS EXAMPLE....";
     
        Optional<String> checkNull = Optional.ofNullable(str[5]);
   
        // It Checks, value is present or not
        if(checkNull.isPresent()){  
       
         String lowercaseString = str[5].toLowerCase();
         
         System.out.print(lowercaseString);
     
        }else
            System.out.println("String value is not present");
    }
}

output :

java optional class example....

Example4 :-
import java.util.Optional;

public class OptionalExample4 {

 public static void main(String[] args) {
     
  String[] str = new String[10];      
     
  // Setting value for 5th index
  str[5] = "JAVA OPTIONAL CLASS EXAMPLE4";  
     
  Optional<String> checkNull = Optional.ofNullable(str[5]);
 
  // printing value by using method reference
        checkNull.ifPresent(System.out::println);
     
     // printing value by using get method
        System.out.println(checkNull.get());  
     
        System.out.println(str[5].toLowerCase());  
    }
}

output :

JAVA OPTIONAL CLASS EXAMPLE4
JAVA OPTIONAL CLASS EXAMPLE4
java optional class example4



6> Lambda Expression :-

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection. Before lambda expression, anonymous inner class was the only option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java lambda expression is treated as a function, so compiler does not create .class file.

    or in other words, A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expression,you can write local functions that can be passed as arguments or returned as the value of function calls.  

Why we use lambda expression ?
1>Less coding
2>It provides the implementations to functional interface. 


Java Lambda expression Syntax :-
1.    (argument-list) -> {body}  

Java lambda expression is consisted of three components.
1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.

lets see...

1-A lambda expression can have zero, one or more parameters.
2-The type of the parameters can be explicitly declared or it can be inferred from the context.        e.g. (String str) is same as just (str)
3-Parameters are enclosed in parentheses and separated by commas. e.g. (a, b) or (double d, int b) or (String str, int b, float f)
4-Empty parentheses are used to represent an empty set of parameters. e.g. () -> 102
5-When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses.      e.g. b -> return b*b
6-The body of the lambda expressions can contain zero, one or more statements.
7-If body of lambda expression has single statement curly brackets are not mandatory and the    return type of the anonymous function is the same as that of the body expression.
8-When there is more than one statement in body than these must be enclosed in curly brackets (a   code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

Java Functional Interfaces

Functional interface are nothing but, it is An interface with exactly one abstract method is known as Functional Interface, it is a Single Abstract Method interface(SAM interface).

           A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.
          

           Functional interfaces are long awaited and much sought out feature of Java 8 because it enables us to use lambda expressions to instantiate them. A new package java.util.function with bunch of functional interfaces are added to provide target types for lambda expressions and method references. We will look into functional interfaces and lambda expressions in the future posts.

Note:- It is an anonymous function also. i.e. a function with no name

Example1 :-Java program without lambda expressions 


interface CheckMoney{ 
    public void check(); 
public class LambdaExpressionExample1 { 
    public static void main(String[] args) { 
        int numberOfNotes=10; 

   //without lambda, CheckMoney implementation 
   //using anonymous class 
        CheckMoney d=new CheckMoney(){ 
    public void check(){System.out.println("Checking number of Notes is : "+numberOfNotes);} 
        }; 
        d.check(); 
    } 
}  
    
output :

Checking number of Notes is : 10


Example2 :-Java program with lambda expressions 


interface CheckMoney{ 
    public void check(); 
public class LambdaExpressionExample2 { 
    public static void main(String[] args) { 
        int numberOfNotes=10; 

        //with lambda, CheckMoney implementation 
        //using anonymous class 
        CheckMoney d=()->{ 
         {System.out.println("Checking number of Notes is : "+numberOfNotes);} 
        }; 
        d.check(); 
    } 
}  

output :

Checking number of Notes is : 10


Example3 :-Java program lambda expressions : No Parameter

interface CheckMoney{ 
    public String check(); 
public class LambdaExpressionExample3 { 
    public static void main(String[] args) { 
       

        //with lambda, CheckMoney implementation 
       //using anonymous class 
        CheckMoney d=()->{ 
         return "I have nothing to check";
        
        }; 
        System.out.println(d.check());
    } 
}  

output :

 I have nothing to check


Example4 :-Java program lambda expressions : One Parameter

interface CheckMoney{ 
    public String check(Integer numberofnotes); 
public class LambdaExpressionExample4 { 
    public static void main(String[] args) { 
       

        //with lambda, CheckMoney implementation 
    //using anonymous class for single parameters
        CheckMoney d=(Notes)->{ 
         return "I have number of notes is : "+Notes;
        
        }; 
        System.out.println(d.check(40));
        CheckMoney d1=(Notes)->{ 
            return "I have number of notes is : "+Notes;
           
           }; 
           System.out.println(d1.check(120));
    } 
}  

output :

I have number of notes is : 40
I have number of notes is : 120

Example4 :-Java program lambda expressions : One Parameter

     interface Additions{ 
      int add(int i,int j); 
      } 

public class LambdaExpressionExample5{ 
    public static void main(String[] args) { 
         
        // Multiple parameters in lambda expression 
        Additions ad1=(i,j)->(i+j); 
        System.out.println(ad1.add(11,12)); 
          
        // Multiple parameters with data type in lambda expression 
        Additions ad2=(int i,int j)->(i+j); 
        System.out.println(ad2.add(13,120)); 
    } 
}  

output :

23
133

Example6 :-Java program lambda expressions : with or without return statements 

 interface Additions{ 
    int add(int i,int j); 

public class LambdaExpressionExample6{ 
    public static void main(String[] args) { 
         
    // Lambda expression without return statement.
        Additions ad1=(i,j)->(i+j); 
        System.out.println(ad1.add(11,12)); 
         
     // Lambda expression with return statement. 
        Additions ad2=(int i,int j)->{
           return (i+j);
        }; 
        System.out.println(ad2.add(13,120)); 
    } 
}  

output :
23
133


Example7 :-Java program lambda expressions : forEach() method

import java.util.*; 
public class LambdaExpressionExample7{ 
    public static void main(String[] args) { 
         
        List<String> list=new ArrayList<String>(); 
        list.add("rani"); 
        list.add("rekha"); 
        list.add("roli"); 
        list.add("rajni"); 
         
        list.forEach( 
            (i)->System.out.println(i
        ); 
    } 


output :
rani
rekha
roli
rajni

Example8 :-Java program lambda expressions : Multiple Parameters

@FunctionalInterface 
interface Sayable{ 
    String say(String message); 

public class LambdaExpressionExample8{ 
    public static void main(String[] args) { 
     
        // You can pass multiple statements in lambda expression 
        Sayable person = (message)-> { 
            String str1 = "I would like to say, "
            String str2 = str1 + message;  
            return str2
        }; 
            System.out.println(person.say("time is precious.")); 
    } 
}

output :

  I would like to say, time is precious. 

Example9 :-Java program lambda expressions : Creating Thread
public class LambdaExpressionExample9{ 
    public static void main(String[] args) { 
     
        //Thread Example without lambda 
        Runnable r1=new Runnable(){ 
            public void run(){ 
                System.out.println("Thread1 is running..."); 
            } 
        }; 
        Thread t1=new Thread(r1); 
        t1.start(); 
        //Thread Example with lambda 
        Runnable r2=()->{ 
                System.out.println("Thread2 is running..."); 
        }; 
        Thread t2=new Thread(r2); 
        t2.start(); 
    } 
}  

output :

Thread1 is running...
Thread2 is running...

Example10 :-Java program lambda expressions : Comparator

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 

class Product{ 
    int id
    String name
    float price
    public Product(int id, String name, float price) { 
        super(); 
        this.id = id
        this.name = name
        this.price = price
    } 
public class LambdaExpressionExample10{ 
    public static void main(String[] args) { 
        List<Product> list=new ArrayList<Product>(); 
         
        //Adding Products 
        list.add(new Product(1,"HP Laptop",25000f)); 
        list.add(new Product(3,"Keyboard",300f)); 
        list.add(new Product(2,"Dell Mouse",150f)); 
         
        System.out.println("Sorting on the basis of name..."); 

        // implementing lambda expression 
        Collections.sort(list,(p1,p2)->{ 
        return p1.name.compareTo(p2.name); 
        }); 
        for(Product p:list){ 
            System.out.println(p.id+" "+p.name+" "+p.price); 
        } 
       
        System.out.println("Sorting on the basis of id..."); 
       
        // implementing lambda expression 
        Collections.sort(list,(p1,p2)->{ 
        return p1.id-p2.id; 
        }); 
        for(Product p:list){ 
            System.out.println(p.id+" "+p.name+" "+p.price); 
        } 

System.out.println("Sorting on the basis of price..."); 
       
        // implementing lambda expression 
        Collections.sort(list,(p1,p2)->{ 
        return (int) (p1.price-p2.price); 
        }); 
        for(Product p:list){ 
            System.out.println(p.id+" "+p.name+" "+p.price); 
        }
    } 
}  

output :
Sorting on the basis of name...
2 Dell Mouse 150.0
1 HP Laptop 25000.0
3 Keyboard 300.0
Sorting on the basis of id...
1 HP Laptop 25000.0
2 Dell Mouse 150.0
3 Keyboard 300.0
Sorting on the basis of price...
2 Dell Mouse 150.0
3 Keyboard 300.0
1 HP Laptop 25000.0


Example11 :-Java program lambda expressions : Filter Collection Data
import java.util.ArrayList; 
import java.util.List; 
import java.util.stream.Stream;  
class Product{ 
    int id
    String name
    float price
    public Product(int id, String name, float price) { 
        super(); 
        this.id = id
        this.name = name
        this.price = price
    } 
public class LambdaExpressionExample11{ 
    public static void main(String[] args) { 
        List<Product> list=new ArrayList<Product>(); 
        list.add(new Product(1,"Samsung A6",17000f)); 
        list.add(new Product(3,"Iphone 6S",64000f)); 
        list.add(new Product(2,"Sony Xperia",26000f)); 
        list.add(new Product(4,"Nokia Lumia",10000f)); 
        list.add(new Product(5,"Redmi3s ",26000f)); 
        list.add(new Product(6,"Lenevo 6K power",21000f)); 
         
        // using lambda to filter data 
        Stream<Product> filtered_data = list.stream().filter(p -> p.price > 20000); 
        System.out.println("Product price more then 20000");
        // using lambda to iterate through collection 
        filtered_data.forEach( 
                product -> System.out.println(product.name+": "+product.price
        );
       
     // using lambda to filter data 
        Stream<Product> filtered_data1 = list.stream().filter(p -> p.price > 40000); 
          System.out.println("Product price more then 40000");
        // using lambda to iterate through collection 
        filtered_data1.forEach( 
                product -> System.out.println(product.name+": "+product.price
        );
    } 
}

output :
Product price more then 20000
Iphone 6S: 64000.0
Sony Xperia: 26000.0
Redmi3s : 26000.0
Lenevo 6K power: 21000.0
Product price more then 40000
Iphone 6S: 64000.0


Example12 :-Java program lambda expressions :Event Listener

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextField; 
public class LambdaExpressionExample12{ 
    public static void main(String[] args) { 
        JTextField tf=new JTextField(); 
        tf.setBounds(50, 50,150,20); 
        JButton b=new JButton("click me"); 
        b.setBounds(80,100,70,20); 
         
        // lambda expression implementing here. 
        b.addActionListener(e-> {tf.setText("Hi first swing");}); 
         
        JFrame f=new JFrame(); 
        f.add(tf);f.add(b); 
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        f.setLayout(null); 
        f.setSize(300, 200); 
        f.setVisible(true); 

    } 


}  

output :

7> Method Reference :-

Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

In other words-

Instead of using
 An ANONYMOUS CLASS
we can use A LAMBDA EXPRESSION
if it is for only one method, we can use A METHOD REFERENCE

There are four type of method reference :-

1> A method reference to a static method
2> A method Reference to a constructor 
3> A method Reference to an instance method of an object of a particular type
4> A method reference to an instance method of an existing object


1> Reference to a static method

  we have lambda expression like :-

 (args) - >Class.staticMethod(args)

but it convert by method reference like this :-

Class :: staticMethod


     You can see that between a static method and a static method reference, instead of the . operator, we use the :: operator, and that we don't pass arguments to the method reference.
      In general, we don't need to pass arguments to method references. However, arguments are treated depending on type of method reference.
       In this case, any arguments (if any) taken by the method are passed automatically behind the curtains.

Syntax :
  ClassName :: staticMethodName


  
import java.util.function.BiFunction; 
class Math
public static int add(int a, int b){ 
return a+b
public class MethodReference01 { 
public static void main(String[] args) { 
BiFunction<Integer, Integer, Integer>adder = Math::add
int result = adder.apply(10, 20); 
System.out.println(result); 
}
















Next Page Coming Soon...


Java 8 New Feature

Java 8 new Feature  ·          forEach() method in Iterable interface. ·          forEachOrdered() method for Java Stream ·         ...