Stream Basics
Introduction to Java Streams
Java Streams provide a powerful way to process collections of objects. Introduced in Java 8, streams allow developers to perform complex data manipulation operations with concise and readable code.
What is a Stream?
A stream is a sequence of elements supporting sequential and parallel aggregate operations. Unlike collections, streams do not store data but process elements from a source such as a collection, array, or I/O channel.
Key Characteristics of Streams
graph TD
A[Stream Characteristics] --> B[Declarative Processing]
A --> C[Functional in Nature]
A --> D[Lazy Evaluation]
A --> E[Potentially Parallel]
Characteristic |
Description |
Declarative |
Describe WHAT to do, not HOW to do it |
Functional |
Use lambda expressions and method references |
Lazy Evaluation |
Compute elements only when needed |
Parallel Processing |
Can leverage multi-core architectures |
Creating Streams
// Stream from collection
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> nameStream = names.stream();
// Stream from array
String[] array = {"Apple", "Banana", "Cherry"};
Stream<String> arrayStream = Arrays.stream(array);
// Stream.of method
Stream<Integer> numberStream = Stream.of(1, 2, 3, 4, 5);
Basic Stream Operations
Filtering
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
Mapping
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
Reducing
Optional<String> longestName = names.stream()
.reduce((name1, name2) ->
name1.length() > name2.length() ? name1 : name2);
When to Use Streams
- Processing collections
- Transforming data
- Performing complex calculations
- Implementing functional programming patterns
Streams are powerful but not always the most performant solution. For small collections or performance-critical code, traditional loops might be more efficient.
Learning with LabEx
At LabEx, we recommend practicing stream operations through hands-on coding exercises to build practical skills and intuition.