Combining lines with Stream Operations
What you'll learn: How to chain lines() with Stream operations to filter, map, and collect text lines efficiently in Java.
The Power of Stream Pipelines
The lines() method returns a Stream<String>, which means you can leverage the entire Stream API to process text. Think of it as a production line: each line of text passes through a series of workstations (Stream operations) where it's filtered, transformed, or collected according to your needs.
Common Patterns
Filtering Lines
Remove blank or unwanted lines using filter():
String text = "Line 1\n\nLine 2\n \nLine 3";
String cleaned = text.lines()
.filter(line -> !line.isBlank())
.collect(Collectors.joining("\n"));
// Result: "Line 1\nLine 2\nLine 3"
Mapping Lines
Transform each line using map():
String text = "hello\nworld";
String uppercase = text.lines()
.map(String::toUpperCase)
.collect(Collectors.joining("\n"));
// Result: "HELLO\nWORLD"
Combining Operations
Chain multiple operations for complex transformations:
String text = " apple \n\n banana \norange\n ";
List<String> processed = text.lines()
.map(String::strip) // Remove leading/trailing spaces
.filter(line -> !line.isEmpty()) // Remove empty lines
.map(s -> s.toUpperCase()) // Convert to uppercase
.collect(Collectors.toList());
// Result: ["APPLE", "BANANA", "ORANGE"]
Real-World Use Cases
- Data cleaning: Remove comments or blank lines from configuration files
- Text transformation: Prefix each line with line numbers or bullets
- Content extraction: Filter lines matching specific criteria
- Reformatting: Join processed lines with different delimiters
Key Takeaway: lines() combined with Stream operations (filter, map, collect) creates powerful, readable pipelines for text processing—transforming multi-line strings becomes a declarative, functional operation.