What is Stream in Java: Simple Explanation and Example
Stream is a sequence of elements that supports functional-style operations to process data easily and efficiently. It allows you to perform tasks like filtering, mapping, and reducing collections in a readable and concise way without modifying the original data.How It Works
Think of a Stream in Java like a conveyor belt in a factory. Items (data elements) move along the belt, and you can perform actions on each item as it passes by, such as sorting, filtering, or transforming it. The stream itself does not store data; it just processes data from a source like a list or array.
This approach lets you write clear and simple code to handle collections of data step-by-step. Instead of writing loops and temporary variables, you describe what you want done, and the stream handles the details. Streams can also process data in parallel, making your program faster on multi-core computers.
Example
This example shows how to use a stream to filter and print even numbers from a list.
import java.util.List; import java.util.stream.Collectors; public class StreamExample { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); } }
When to Use
Use streams when you want to process collections of data in a clear and concise way. They are great for tasks like filtering items, transforming data, or combining results without writing complex loops.
For example, streams are useful when working with lists of users, files, or numbers where you need to find specific items, convert data formats, or calculate summaries. They also help improve readability and can boost performance by enabling parallel processing.
Key Points
- Streams process data without changing the original source.
- They support functional operations like filter, map, and reduce.
- Streams can be sequential or parallel for better performance.
- They make code more readable and concise.