Stream Operations
Stream Operation Categories
graph TD
A[Stream Operations] --> B[Intermediate Operations]
A --> C[Terminal Operations]
Filtering
public class FilteringExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Filter names starting with 'A'
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
}
}
Mapping
public class MappingExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("hello", "world", "java");
// Convert to uppercase
List<String> upperCaseWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
}
}
Terminal Operations
| Operation |
Description |
Return Type |
| collect() |
Collect stream elements into a collection |
Collection |
| forEach() |
Perform action on each element |
void |
| reduce() |
Reduce stream to single value |
Optional |
| count() |
Count stream elements |
long |
Reduction Example
public class ReductionExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Sum of all numbers
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
// Find maximum
Optional<Integer> max = numbers.stream()
.reduce(Integer::max);
}
}
Advanced Stream Techniques
public class AdvancedStreamOperations {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 85),
new Student("Bob", 92),
new Student("Charlie", 78)
);
// Complex stream pipeline
double averageScore = students.stream()
.filter(s -> s.getScore() > 80)
.mapToInt(Student::getScore)
.average()
.orElse(0.0);
}
}
class Student {
private String name;
private int score;
// Constructor, getters, setters
}
Parallel Stream Processing
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Parallel stream processing
int sum = numbers.parallelStream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
}
}
- Intermediate operations are lazy
- Terminal operations trigger stream processing
- Parallel streams can improve performance for large datasets
LabEx Pro Tip
At LabEx, we encourage developers to master Stream operations through consistent practice and understanding of functional programming principles. Experiment with different operations to unlock the full potential of Java Streams!