Saturday, 19 March 2016

Java 8 essentials summary Part I

Functional Interface


Functional Interface may be annotated by @FunctionalInterface. Functional interface has only one abstract method. This implies that functional interface exhibit single functionality. 

This method should not be confuse with default or static method in the interface which have implementation. Also any abstract method overriding one of the public method of java.lang.Object does not count. 

Default Methods in interface

 

Essentially Interface is 100% abstract. It is the responsibility of the classes to provide implementation for all the methods declared in the interface. 

Now we have a scenario where we want to add additional functionality to interface by declaring a new method in it. What will happen to the classes that have implemented the interface? 

Wow!!! All classes will break.

Here’s come Default method in the interface for our rescue. Default method is a method which has default in its signature and it has a concrete implementation. So the classes implementing the interface does not have to mandatory implement it. This helps us extending the interface functionality without breaking all the classes that implement it. There can be only one default method for a functional interface.

Static method in Interface

 

Java 8 provide static method for interface and we provide implementation for the static methods.

Below figure illustrate a simple Functional Interface and some related concept





Lambda

 

Lambda provide a very simple implementation of abstract method of the functional interface. Generic Lambda expression will look like

  (Type arg1.....) -> {   Body   }

Easiest way to visualize the implementation of lambda expression is the implementation of anonymous class as shown in the below figure.

We replace the first part marked in red with (Type arg1..) -> and remove the closing bracket as shown below. That’s All.

Now the question is why we do not need to specify the name of the interface method that will be implemented. This is because functional interface has only one abstract method  that needs to be implemented so it is just obvious what we are going to implemented. JVM has become smart enough to make this inference, also it can determine the type of the parameter required by method so that also we can omit. 

So to summarize we just remove the obvious with Lambda Expression.





There are number of one method interface or functional interface provided by java that can be extensively use with lambda expression.

Below is the illustration for java.lang.Runnable Interface which has run method as how the use of these method become straight forward with Lambda expression.


public class LambdaForOneMethodImpl {

    public static void main(String[] args) {
       
        Runnable r1=new Runnable(){

            @Override
            public void run() {
                System.out.println("You are running run anonymously" );
            }
           
        };

        r1.run();   
       
        Runnable r2=()->{System.out.println("You are running run with Lambda ");};
        r2.run();
    }
  
  
 }




One method interface are java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable.

Java 8 has defined a lot of functional interfaces in java.util.function package and these can be extensively used with lambda expression




Additional resource
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
http://www.tutorialspoint.com/java8/java8_lambda_expressions.htm
http://tutorials.jenkov.com/java/lambda-expressions.html



Saturday, 5 March 2016

Comparator in Java 8

Java 8 comparator can be created from Lambda expression. 

Lambda expression define inline implementation of functional interface. 

A functional interface is an interface which have only one abstract method. This method is neither the default function of the interface nor an abstract method inherited from the Object class.


With java 8, the way the comparator is written become very clean with the removal of boilerplate code.

Pre Java 8 days the format of the comparator will be something like this

//pre java 8
Comparator<Product> nameCompare=new Comparator<Product>(){
public int compare(Product p1,Product p2){
return p1.getName().compareTo(p2.getName());
}
};
listProduct.sort(nameCompare) or Collection.sort(listProduct,nameCompare);



And with Java 8 comparator has become something like this

listProduct.sort( ( Product p1 , Product p2) -> p1.getPrice() - p2.getPrice() );

Now let us see in detail how comparator can be implemented in Java 8 with Lambda


1. Create a Product class:

class Product{
int id;
String name;
double weight;
double price;
Product(int id,String name,double price,double weight){
this.id=id;
this.name=name;
this.weight=weight;
this.price=price;
}

//Getters and Setters


@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", weight=" + weight + ", price=" + price + "]";
}
}

2. Create a method which will initialize product and return a list of product.

private static List<Product> getProductList() {
List<Product> listProduct=new ArrayList<Product>();
Product p1=new Product(1,"Dell",40000.00,2.5);
Product p2=new Product(2,"Lenovo",30000.00,3.5);
Product p3=new Product(3,"Apple",100000.00,2.0);
Product p4=new Product(4,"HP",70000.00,1.5);
Product p5 = new Product(5"HP", 70000.00, 5.5);
listProduct.add(p1);
listProduct.add(p2);
listProduct.add(p3);
listProduct.add(p4);
listProduct.add(p5);
return listProduct;
}

3. Main methods will implement the below use cases
3.1 .  Sort the list of product by name
3.2  Sort the list of product on weight.
3.3  Sort the list of product on price and then on weight.
3.4  Sort by reverse order of price.




Output



 Additional Resource 

Streaming with Kafka API

The Kafka Streams API is a Java library for building real-time applications and microservices that efficiently process and analyze large-sca...