Intermediate Java Day 7: Streams & Lambda Expressions

Goal of this Day

Today you will learn:

By the end, you will be able to use streams and lambdas to process collections concisely.

Step 1: Basic Java Streams

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));

Step 2: filter, map, reduce

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);

Step 3: Lambda Expressions

Lambdas provide a concise way to write anonymous functions.


numbers.forEach(n -> System.out.println(n * 2));

Explanation:

Step 4: Simple Functional Programming

Streams 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);

Practice


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);

Exercise

Use a stream to find the maximum value in a list of integers.

Steps:

Example:


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);
    }
}