Advanced Java Day 3: Streams, Lambda Expressions, and Functional Programming

Goal of this Day

Today you will learn:

By the end, you will be able to use functional programming concepts in Java for concise and efficient data processing.

Step 1: Basic Stream Operations

Streams allow you to perform operations on collections in a functional style.


import java.util.*;
import java.util.stream.*;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

List<Integer> even = numbers.stream()
                                .filter(n -> n % 2 == 0)
                                .collect(Collectors.toList());

even.forEach(System.out::println);

Step 2: Map and Reduce

Use map to transform elements and reduce to combine results.


int sumOfSquares = numbers.stream()
                          .filter(n -> n % 2 != 0) // odd numbers
                          .map(n -> n * n)         // square each
                          .reduce(0, Integer::sum); // sum
System.out.println("Sum of squares of odd numbers: " + sumOfSquares);

Step 3: Parallel Streams

Parallel streams can improve performance for large collections by processing elements concurrently.


int sumParallel = numbers.parallelStream()
                         .filter(n -> n % 2 != 0)
                         .map(n -> n * n)
                         .reduce(0, Integer::sum);

System.out.println("Parallel sum: " + sumParallel);

Step 4: Lambda Expressions with Collections

Lambdas provide a concise way to pass behavior to collection methods.


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

Step 5: Method References

Method references are a shorthand for lambdas that call an existing method.


numbers.forEach(System.out::println);

Practice


import java.util.*;
import java.util.stream.*;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> even = numbers.stream()
                                .filter(n -> n % 2 == 0)
                                .collect(Collectors.toList());
even.forEach(System.out::println);

Exercise

Use streams to find the sum of squares of all odd numbers in a list.

Steps:

Example:


import java.util.*;
import java.util.stream.*;

public class SumSquaresOdd {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

        int sumOfSquares = numbers.stream()
                                  .filter(n -> n % 2 != 0)
                                  .map(n -> n * n)
                                  .reduce(0, Integer::sum);

        System.out.println("Sum of squares of odd numbers: " + sumOfSquares);
    }
}