Thursday, January 16, 2025
HomeProgrammingWhat is Stream in Java?

What is Stream in Java?

In Java, a Stream is a sequence of elements that can be processed in parallel or sequentially. Introduced in Java 8, Streams provide a functional approach to process collections, arrays, or I/O channels.

They allow operations like filtering, mapping, sorting, and collecting, making code more readable and expressive.

See also  How do I Delete Everything in Redis?

Streams are not data structures; they do not store data but convey elements from a source (like a collection). Key operations on Streams include:

1. Intermediate operations: Transform the data (e.g., filter(), map(), sorted()) and return a new stream.

See also  Arrays in Java

2. Terminal operations: Produce a result or side effect (e.g., collect(), forEach(), reduce(), count()).

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n > 2)
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 12

Streams enable efficient data processing, especially when dealing with large datasets or parallel operations.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x