Friday, 26 May 2017

Java Lambda expressions[How to sort the list of product using lambda expression - Comparator]


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=r8zFhM04L_A&list=UUhwKlOVR041tngjerWxVccw

Product.java
class Product
{
    private int id;
    private String name;
    private float price;

    public Product(int id, String name, float price)
    {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public float getPrice()
    {
        return price;
    }

    public void setPrice(float price)
    {
        this.price = price;
    }

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

/**
 * Java Lambda Expression Example: Comparator
 *
 */
public class LambdaDemo
{

    public static void main(String[] args)
    {
        List<Product> list = new ArrayList<Product>();

        // Adding Products
        list.add(new Product(1, "Sony LED TV", 65000f));
        list.add(new Product(2, "Radio", 3000f));
        list.add(new Product(3, "Laptop", 150000f));

        System.out.println("Before Sorting .... \n");

        displayProductInfo(list);

        System.out.println("\nAfter Sorting ...\n");

        // implementing lambda expression
        Collections.sort(list, (p1, p2) -> {
            return p1.getName().compareTo(p2.getName());
        });

        displayProductInfo(list);
    }

    private static void displayProductInfo(List<Product> list)
    {
        for (Product p : list)
        {
            System.out.println(p.getId() + " " + p.getName() + " "
                    + p.getPrice());
        }
    }

}
Output
Before Sorting .... 

1 Sony LED TV 65000.0
2 Radio 3000.0
3 Laptop 150000.0

After Sorting ...

3 Laptop 150000.0
2 Radio 3000.0
1 Sony LED TV 65000.0
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/LambdaDemo_product_sort_name_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/LambdaDemo_product_sort_name_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/a195090f4adc5a52ed7df4d076a2367bfb5b1fbe/BasicJava/LambdaDemo_product_sort_name_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge