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.
Stream provides following features:
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.
Recommended by LinkedIn
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