DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

Stream in Java

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.
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.

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;

}

}

public class JavaStreamExample {

public static void main(String[] args) {

List productsList = new ArrayList();

//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));

List 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);

}

}

Read full article : https://www.javatpoint.com/java-8-stream

Top comments (0)