DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

1 1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay