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 

No comments:

Post a Comment

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...