Today you will learn:
filter, map, reduceBy the end, you will be able to use streams and lambdas to process collections concisely.
Streams allow you to perform operations on collections in a functional style.
import java.util.Arrays;
import java.util.List;
List numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().forEach(n -> System.out.println(n));
Streams support operations like filter, map, and reduce.
// Sum of even numbers
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n)
.sum();
System.out.println("Sum of even numbers: " + sum);
Lambdas provide a concise way to write anonymous functions.
numbers.forEach(n -> System.out.println(n * 2));
Explanation:
n -> n * 2 is a lambda taking n and returning n*2Streams allow chaining multiple operations for concise and readable code.
int maxEven = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n)
.max()
.orElse(0);
System.out.println("Maximum even number: " + maxEven);
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n)
.sum();
System.out.println("Sum of even numbers: " + sum);
Use a stream to find the maximum value in a list of integers.
Steps:
stream() with max()filter or map before finding the maxExample:
import java.util.Arrays;
import java.util.List;
public class MaxValueStream {
public static void main(String[] args) {
List numbers = Arrays.asList(10, 3, 25, 7, 18);
int max = numbers.stream()
.max(Integer::compare)
.orElse(Integer.MIN_VALUE);
System.out.println("Maximum value: " + max);
}
}