Java Streams

Java 8 Stream API: filter, map, reduce, collect, and functional programming operations.

Creating Streams

// From collection
List list = Arrays.asList("a", "b", "c");
Stream stream = list.stream();  # create stream

// From array
String[] arr = {"a", "b", "c"};
Stream stream = Arrays.stream(arr);

// Using Stream.of()
Stream stream = Stream.of(1, 2, 3, 4, 5);

Filter

// Filter elements
List numbers = Arrays.asList(1, 2, 3, 4, 5);

// Get even numbers
List evens = numbers.stream()
    .filter(n -> n % 2 == 0)  # keep only even
    .collect(Collectors.toList());

Map

// Transform elements
List names = Arrays.asList("john", "jane");

// Convert to uppercase
List upper = names.stream()
    .map(String::toUpperCase)  # transform each
    .collect(Collectors.toList());

// Get length of strings
List lengths = names.stream()
    .map(String::length)  # get string lengths
    .collect(Collectors.toList());

Reduce

// Reduce to single value
List nums = Arrays.asList(1, 2, 3, 4, 5);

// Sum all numbers
int sum = nums.stream()
    .reduce(0, (a, b) -> a + b);  # returns 15

// Find product
int product = nums.stream()
    .reduce(1, (a, b) -> a * b);  # returns 120

Collect

// Collect to List
List list = stream.collect(Collectors.toList());

// Collect to Set
Set set = stream.collect(Collectors.toSet());  # unique only

// Join strings
String joined = stream.collect(Collectors.joining(", "));  # a, b, c

Find & Match

// Find first
Optional first = list.stream()
    .findFirst();  # get first element

// Check if any match
boolean hasEven = nums.stream()
    .anyMatch(n -> n % 2 == 0);  # true if any even

// Check if all match
boolean allPositive = nums.stream()
    .allMatch(n -> n > 0);  # true if all positive

Sorting

// Sort ascending
List sorted = nums.stream()
    .sorted()  # natural order
    .collect(Collectors.toList());

// Sort descending
List desc = nums.stream()
    .sorted(Comparator.reverseOrder())  # reverse order
    .collect(Collectors.toList());

Advanced Operations

// Distinct elements
list.stream().distinct()  # remove duplicates

// Limit elements
list.stream().limit(5)  # first 5 elements

// Skip elements
list.stream().skip(3)  # skip first 3

// Count elements
long count = list.stream().count();  # number of elements