Click here to watch in Youtube :https://www.youtube.com/watch?v=XBtsIW7_H_k&list=UUhwKlOVR041tngjerWxVccwProduct.javapublic 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.javaimport 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);
}
}
OutputproductNameList = [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=1Github Link:https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_Collectors_toList_joiningBitbucket Link:https://bitbucket.org/ramram43210/java/src/adf72ea7a150b1a34af5820c19f2232b522614b9/BasicJava/StreamDemo_Collectors_toList_joining/?at=masterSee also: All JavaEE Viedos PlaylistAll JavaEE ViedosAll JAVA EE LinksServlets TutorialAll Design Patterns LinksJDBC TutorialJava Collection Framework TutorialJAVA TutorialKids Tutorial