Thursday, 8 June 2017

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


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

No comments:

Post a Comment