03 Stream
03 Stream
• Streams are NOT data structures but are wrappers around Collection
that carry values from a source through a pipeline of operations.
• Streams are more powerful, faster and more memory efficient than
Lists
The elements of a stream are only visited once during the life of a
stream. Like an Iterator, a new stream must be generated to revisit
the same elements of the source.
You can use stream to filter, collect, print, and convert from one
data structure to other etc. In the following examples, we have
apply various operations with the help of stream.
productsList.stream()
.filter(product -> product.price == 30000)
.forEach(product -> System.out.println(product.name));
Map<Integer,String> productPriceMap =
productsList.stream()
.collect(Collectors.toMap(p->p.id, p->p.name));
System.out.println(productPriceMap);
Output
{1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop,
5=Apple Laptop}
//Adding Products
productsList.add(new Product(1,"HP Laptop",25000f));
productsList.add(new Product(2,"Dell Laptop",30000f));
productsList.add(new Product(3,"Lenevo Laptop",28000f));
productsList.add(new Product(4,"Sony Laptop",28000f));
productsList.add(new Product(5,"Apple Laptop",90000f));