Wednesday 20 September 2017

How to use collectingAndThen method of Collectors | Java 8 streams | Streams in Java 8


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

Product.java
public class Product
{
    private String name;
    private int price;

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

    public String getName()
    {
        return name;
    }

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

    public int getPrice()
    {
        return price;
    }

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

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

}
StreamDemo.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamDemo
{
    public static void main(String[] args)
    {
        List<Product> productList = Arrays.asList(
                new Product("potatoes", 15),
                new Product("orange", 15), new Product("lemon", 20),
                new Product("bread", 20), new Product("sugar", 30));

        /*
         * Pushing the collector to perform additional transformation:
         * 
         * The collector has converted a stream to a Set and then
         * created the unmodifiable Set out of it.
         */
        Set<Product> unmodifiableSet = productList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toSet(),
                        Collections::unmodifiableSet));

        System.out.println("unmodifiableSet = " + unmodifiableSet);
        
    }

}
Output
unmodifiableSet = [Product [name=orange, price=15], Product [name=lemon, price=20], 
Product [name=potatoes, price=15], Product [name=sugar, price=30], 
Product [name=bread, price=20]]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_unmodifiable_set.zip?attredirects=0&d=1

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/adf72ea7a150b1a34af5820c19f2232b522614b9/BasicJava/StreamDemo_unmodifiable_set/?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