Tuesday 19 September 2017

How to use toList and joining methods of Collectors | Java 8 streams | Streams in Java 8


Click here to watch in Youtube :
https://www.youtube.com/watch?v=XBtsIW7_H_k&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.List;
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));

        /*
         * Converting a stream to the Collection (Collection, List or
         * Set):
         */
        List<String> productNameList = productList.stream()
                .map(Product::getName).collect(Collectors.toList());

        System.out.println("productNameList = " + productNameList);

        /*
         * Reducing to String:
         * 
         * The joiner() method can have from one to three parameters
         * (delimiter, prefix, suffix). The handiest thing about using
         * joiner() – developer doesn’t need to check if the stream
         * reaches its end to apply the suffix and not to apply a
         * delimiter. Collector will take care of that.
         */

        String listToString = productList.stream()
                .map(Product::getName)
                .collect(Collectors.joining(", ", "[", "]"));

        System.out.println("listToString = " + listToString);

    }

}
Output
productNameList = [potatoes, orange, lemon, bread, sugar]
listToString = [potatoes, orange, lemon, bread, sugar]

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

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

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