Stream
Anshu Tiwari, CSE
Introduction
Java provides a new additional package in Java 8 called
java.util.stream. This package consists of classes, interfaces and
enum to allows functional-style operations on the elements.
Anshu Tiwari, CSE
Characteristics of Streams
• Streams are not related to InputStreams, OutputStreams, etc.
• 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
• Streams are designed for lambdas
Anshu Tiwari, CSE
Characteristics of Streams
• Streams can easily be output as arrays or lists
• Streams employ lazy evaluation
• Streams are parallelizable
Anshu Tiwari, CSE
Stream provides following features:
Stream does not store elements. It simply conveys elements from a
source such as a data structure, an array, or an I/O channel, through a
pipeline of computational operations.
Stream is functional in nature. Operations performed on a stream does
not modify it's source. For example, filtering a Stream obtained from a
collection produces a new Stream without the filtered elements, rather
than removing elements from the source collection.
Anshu Tiwari, CSE
Stream provides following features:
Stream is lazy and evaluates code only when required.
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.
Anshu Tiwari, CSE
Filtering Collection without using Stream
import java.util.*;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
Anshu Tiwari, CSE
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
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));
Anshu Tiwari, CSE
List<Float> productPriceList = new ArrayList<Float>();
for(Product product: productsList){
if(product.price<30000) // filtering data of list
// adding price to a productPriceList
productPriceList.add(product.price);
}
System.out.println(productPriceList); // displaying data
}
}
Anshu Tiwari, CSE
Filtering Collection by using Stream
import java.util.*;
import java.util.stream.Collectors;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
Anshu Tiwari, CSE
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
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));
Anshu Tiwari, CSE
List<Float> productPriceList2 =productsList.stream()
.filter(p -> p.price > 30000)// filtering data
.map(p->p.price) // fetching price
.collect(Collectors.toList()); // collecting as list
System.out.println(productPriceList2);
}
}
Anshu Tiwari, CSE
Java Stream Iterating Example
Output
import java.util.stream.*;
5
public class JavaStreamExample {
public static void main(String[] args){ 10
Stream.iterate(1, element->element+1) 15
.filter(element->element%5==0) 20
.limit(5) 25
.forEach(System.out::println);
}
}
Anshu Tiwari, CSE
Filtering and Iterating Collection
productsList.stream()
.filter(product -> product.price == 30000)
.forEach(product -> System.out.println(product.name));
Anshu Tiwari, CSE
reduce() Method in Collection
Float totalPrice = productsList.stream()
.map(product->product.price)
// accumulating price
.reduce(0.0f,(sum, price)->sum+price);
System.out.println(totalPrice);
Anshu Tiwari, CSE
reduce() Method in Collection
float totalPrice2 = productsList.stream()
.map(product->product.price)
// accumulating price, by referring method of Float class
.reduce(0.0f,Float::sum);
System.out.println(totalPrice2);
Anshu Tiwari, CSE
Sum by using Collectors Methods
double totalPrice3 = productsList.stream()
.collect(Collectors.summingDouble(product->product.price));
System.out.println(totalPrice3);
Anshu Tiwari, CSE
Find Max and Min Product Price
// max() method to get max Product price
Product productA = productsList.stream().max((product1, product2)
->product1.price > product2.price ? 1: -1).get();
System.out.println(productA.price);
// min() method to get min Product price
Product productB = productsList.stream().min((product1, product2)
->product1.price > product2.price ? 1: -1).get();
System.out.println(productB.price);
Anshu Tiwari, CSE
count() Method in Collection
long count = productsList.stream()
.filter(product->product.price<30000)
.count();
System.out.println(count);
Anshu Tiwari, CSE
Convert List into Set
Set<Float> productPriceList = productsList.stream()
// filter product on the base of price
.filter(product>product.price < 30000)
.map(product->product.price)
// collect it as Set(remove duplicate elements)
.collect(Collectors.toSet());
System.out.println(productPriceList);
Anshu Tiwari, CSE
Convert List into Map
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}
Anshu Tiwari, CSE
Method Reference in stream
import java.util.*;
import java.util.stream.Collectors;
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
Anshu Tiwari, CSE
public int getId() {
return id;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
}
Anshu Tiwari, CSE
public class JavaStreamExample {
public static void main(String[] args) {
List<Product> productsList = new ArrayList<Product>();
//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));
Anshu Tiwari, CSE
List<Float> productPriceList =
productsList.stream()
// filtering data
.filter(p -> p.price > 30000)
// fetching price by referring getPrice method
.map(Product::getPrice)
// collecting as list
.collect(Collectors.toList());
System.out.println(productPriceList);
}
}
Anshu Tiwari, CSE