Scaler Topics LogoScaler Topics Logo
Search for Articles, Topics

Streams in Java- Complete Tutorial with Examples

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Start Learning View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Streams in Java, a feature introduced in Java 8, revolutionized data processing by offering a functional and declarative approach. They enable developers to perform sequential or parallel aggregate operations on sequences of objects efficiently.

The Stream API in Java provides a collection of stream classes that facilitate the manipulation and transformation of data. These streams allow developers to write expressive and concise code while maintaining high efficiency.

Understanding streams in Java is paramount for modern Java developers. They empower developers to write code that is efficient and easy to read and maintain. By leveraging streams, developers can efficiently perform complex data processing tasks, leading to cleaner and more maintainable codebases.

See Also: Complete Java Tutorial

Java Stream Features

Functional-style operations: Streams support functional-style operations like map, filter, and reduce, which enable developers to express data processing logic in a more declarative and readable way.

Pipelining: Streams enable the seamless chaining of operations into a pipeline, where the result of each operation feeds directly into the next. This enables efficient and compact code without the need for intermediate collections.

Lazy evaluation: Streams employ lazy evaluation, meaning intermediate operations are only executed once a terminal operation is invoked. This improves efficiency by avoiding unnecessary computation.

Parallel processing: Streams can be processed in parallel, leveraging multi-core architectures to improve performance for large datasets. Parallel streams automatically divide the data into multiple chunks and process them concurrently.

Streams in Java provide a powerful and efficient way to process data by applying various sequential and parallel aggregate operations. The Stream API in Java 8 introduced the concept of streams and stream classes in Java, which offer specialized functionality for manipulating and transforming data. Developers can utilize the Stream API in Java to write more concise, expressive, and efficient code.

The Stream API in Java provides a rich set of operations that can be applied to streams, such as filtering, mapping, and reducing. The Stream API in Java provides a high-level abstraction for working with streams and offers a wide range of operations to manipulate and process data.

Introduction of Streams in Java

Example of Streams in Java

Here's an example that demonstrates the use of Streams in Java to filter and transform a collection of names:

In this example, we create a stream from the names list, filter the names starting with "J", convert them to uppercase using the map operation, and collect the results into a new list using the collect terminal operation. The output is the filtered and transformed names: [JOHN, JANE].

How to Create Java Stream?

Java streams can be created in many ways, including creating an empty stream, a stream from an existing array, a stream from specified values, etc. Streams in java are declared as:

Syntax

Depending upon the declaration, T is either a class, object, or data type.

Different Operations on Streams in Java

Stream provides various operations that can be chained together to produce results. Stream operations can be classified into two types.

  • Intermediate Operations
  • Terminal Operations

1. Intermediate Operations

It returns a stream as the output and intermediate operations are only executed once a terminal operation is invoked on the stream. This is called lazy evaluation, which is discussed in detail in the later section (Lazy Evaluation).

2. Terminal Operations

Terminal operations in streams produce the final results of the stream after all intermediate operations have been applied, marking the end of stream processing. Once a terminal operation is executed, the stream cannot be further utilized.

Java Stream Interface Methods

MethodsDescription
Stream<T> distinct()It produces a stream containing unique elements based on their equality defined by the equals method.
Optional<T> findAny()It returns an Optional containing an element from the stream, if present, or an empty Optional if the stream is empty.
void forEach(Consumer<? super T> action)It executes a specific action for every element within the stream.
Stream<T> limit(long maxSize)This method returns a stream containing elements from the original stream, limited to a maximum length of maxSize.
Stream<T> peek(Consumer<? super T> action)It produces a stream containing the elements of the original stream while executing a specified action on each element as it is processed.
Stream<T> sorted()The sorted() method returns a stream with elements sorted in natural order. If the elements are not comparable, it may result in a ClassCastException during terminal operations.
Object[] toArray()It collects the elements of the stream into an array and returns it.
boolean anyMatch(Predicate<? super T> predicate)It retrieves the first element from the stream that matches the given predicate. If the stream is empty, it returns false without evaluating the predicate.
static <T> Stream.Builder<T> builder()It returns a builder for a Stream.
boolean allMatch(Predicate<? super T> predicate)it return all the matched elements with given predicate.
<R,A> R collect(Collector<? super T,A,R> collector)It conducts a mutable reduction operation on the stream elements using a Collector, enabling flexible collection strategies and composing collect operations like grouping or partitioning.
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)It creates a concatenated stream by combining elements from two input streams. The resulting stream inherits ordering and parallelism properties from the input streams and invokes close handlers for both when closed.

Example of Java Stream

Output

Conclusion

  1. Streams in Java provide a sequence of objects that support various sequential and parallel aggregate operations.
  2. The Stream API in Java offers both intermediate and terminal operations that can be applied to stream instances.
  3. Intermediate operations, such as filter, map, and sorted, return a new stream and are lazily evaluated, meaning they are only executed once a terminal operation is invoked.
  4. Terminal operations, including forEach, collect, min, and max, produce the final results of the stream.
  5. Some stream operations are short-circuiting, allowing early termination without processing all elements in the stream.
  6. Lazy evaluation is a fundamental characteristic of streams in Java, ensuring that intermediate operations are performed only when a terminal operation is invoked.

哆哆女性网reshade下载罗起名男平台经济反垄断指南农业种植养殖公司起名双胞胎起名2020年最强教育培训学校起名大全任仲平是谁慈溪网给班级起个名字杜起名字给牧羊犬适合起什么名字好听怅然若失2019年猪年起名字猪小孩起名易用字老兵纹身写小说起名字万能显卡郭姓起什么名字的电子请帖offer是什么怎么戴假发工作室起名测试小说老婆爱上我网上挂号预约平台君临九天阿爸阿妈原唱昌起名转正申请书范文小孩子在线起名淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻不负春光新的一天从800个哈欠开始有个姐真把千机伞做出来了国产伟哥去年销售近13亿充个话费竟沦为间接洗钱工具重庆警方辟谣“男子杀人焚尸”男子给前妻转账 现任妻子起诉要回春分繁花正当时呼北高速交通事故已致14人死亡杨洋拄拐现身医院月嫂回应掌掴婴儿是在赶虫子男孩疑遭霸凌 家长讨说法被踢出群因自嘲式简历走红的教授更新简介网友建议重庆地铁不准乘客携带菜筐清明节放假3天调休1天郑州一火锅店爆改成麻辣烫店19岁小伙救下5人后溺亡 多方发声两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#青海通报栏杆断裂小学生跌落住进ICU代拍被何赛飞拿着魔杖追着打315晚会后胖东来又人满为患了当地回应沈阳致3死车祸车主疑毒驾武汉大学樱花即将进入盛花期张立群任西安交通大学校长为江西彩礼“减负”的“试婚人”网友洛杉矶偶遇贾玲倪萍分享减重40斤方法男孩8年未见母亲被告知被遗忘小米汽车超级工厂正式揭幕周杰伦一审败诉网易特朗普谈“凯特王妃P图照”考生莫言也上北大硕士复试名单了妈妈回应孩子在校撞护栏坠楼恒大被罚41.75亿到底怎么缴男子持台球杆殴打2名女店员被抓校方回应护栏损坏小学生课间坠楼外国人感慨凌晨的中国很安全火箭最近9战8胜1负王树国3次鞠躬告别西交大师生房客欠租失踪 房东直发愁萧美琴窜访捷克 外交部回应山西省委原副书记商黎光被逮捕阿根廷将发行1万与2万面值的纸币英国王室又一合照被质疑P图男子被猫抓伤后确诊“猫抓病”

哆哆女性网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化