Stream API

Stream API

Hello connections,

In this article, you will learn about Java Stream API.

Java Stream API:

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. You can use stream by importing java.util.stream package.

No alt text provided for this image


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.

Example Stream Filter:

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only warranty products of your list then you can do this easily with the help of filter method.

This method takes predicate as an argument and returns a stream of consisting of resulted elements

Implementation of stream filter:

public List<Product> getProductswithInWarranty() {
        int currentYear = Year.now().getValue();
        return products.stream()
                .filter(p -> p.getWarranty() > currentYear)
                .toList();
    }        

Result:

=============================================
get all products in warranty
Product{name='Type C', type='Cable', place='Black Drawer', warranty=2024}
Product{name='Mac Studio', type='Computer', place='White Table', warranty=2025}
Product{name='Focusrite Mixer', type='Audio System', place='White Table', warranty=2025}
Product{name='Logitech Keyboard', type='Keyboard', place='Black Table', warranty=2024}
Product{name='Hdmi cable', type='Cable', place='Black Drawer', warranty=2024}
Product{name='Java Black Book', type='Cable', place='Shelf', warranty=2024}=        

GitHub Link for complete code

To view or add a comment, sign in

More articles by Prudvi Raj Mokkapalli

  • Recursion & Memoization

    Hello connections, In this article, you will learn about Recursion and Memoization using Java. Recursion: Recursion is…

Insights from the community

Others also viewed

Explore topics