A Lambda Expression is just a shorthand way to write a tiny method in one line. It looks like this: (input) -> expression.
The Stream Pipeline
filter: Keeps only the items that match a condition.map: Transforms each item (e.g., turning text to Uppercase).sorted: Reorders the items.collect: Gathers the final results back into a List.
The Code Example:
import java.util.*;
import java.util.stream.*;
public class ModernJavaDemo {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Amy", "David");
System.out.println("Original List: " + names);
// --- The Modern Pipeline ---
// Goal: Find names starting with 'A', make them Uppercase, and Sort them.
List<String> result = names.stream()
.filter(name -> name.startsWith("A")) // Lambda: Keep only 'A' names
.map(name -> name.toUpperCase()) // Lambda: Convert to Uppercase
.sorted() // Sort alphabetically
.collect(Collectors.toList()); // Turn back into a List
System.out.println("Processed List: " + result);
// --- Quick Math with Streams ---
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sumOfEvens = numbers.stream()
.filter(n -> n % 2 == 0) // Keep only even numbers
.mapToInt(n -> n * n) // Square them: (2->4, 4->16)
.sum(); // Add them up (4 + 16)
System.out.println("Sum of squares of even numbers: " + sumOfEvens);
}
}Expected Output:
Original List: [Alice, Bob, Charlie, Amy, David]
Processed List: [ALICE, AMY]
Sum of squares of even numbers: 20