Wednesday, January 8, 2025
HomeProgrammingStream API

Stream API

The Stream API in Java is a powerful feature introduced in Java 8 for working with sequences of elements (such as collections) in a functional style. It allows for more readable and concise code when performing operations on data, such as filtering, mapping, and reducing.

Key Concepts:

  • Stream: A sequence of data elements supporting aggregate operations.
  • Intermediate Operations: Operations that transform the stream (e.g., filter(), map(), sorted()).
  • Terminal Operations: Operations that produce a result or a side-effect (e.g., collect(), forEach(), reduce()).
See also  Java String substring() Method

Example:

java
import java.util.Arrays;
import java.util.List;

public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Using Stream API to filter even numbers and print them
numbers.stream()
.filter(n -> n % 2 == 0) // Intermediate operation
.forEach(System.out::println); // Terminal operation
}
}

Common Stream Operations:

  • filter(): Filters elements based on a condition.
  • map(): Transforms elements.
  • sorted(): Sorts elements.
  • reduce(): Combines elements into a single result.
  • collect(): Collects elements into a collection like List, Set, etc.

Benefits:

  • Concise and Readable: Reduces boilerplate code.
  • Parallel Processing: Can easily leverage multi-core architectures with .parallelStream().
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