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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay