Module 9 of 30 · Java Programming — Core to Enterprise · Intermediate

Streams and Lambda Expressions

Duration: 7 min

This module delves into Java Streams and Lambda Expressions, two powerful features introduced in Java 8 that enhance the way we process collections of data. Understanding these concepts is crucial for writing efficient and concise code, especially in enterprise applications where performance and readability are key.

Lambda Expressions

Lambda expressions provide a clear and concise way to represent a single method interface using an expression. They are similar to methods, but they do not need a name and they can be implemented right in the body of a method. This feature is particularly useful for functional programming and for making code more readable and maintainable.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Example1 {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Predicate lambda expression to filter names starting with 'A'
        Predicate<String> startsWithA = name -> name.startsWith("A");

        // Using the lambda expression with the stream API
        names.stream()
            .filter(startsWithA)
            .forEach(System.out::println);
    }
}
Alice

Streams

Streams are a sequence of elements supporting sequential and parallel aggregate operations. They are used to process data in a declarative way, which means you describe what you want to do, not how to do it. This leads to more readable and maintainable code, especially when dealing with complex data processing tasks.

import java.util.List;
import java.util.stream.Collectors;

public class Example2 {
    public static void main(String[] args) {
        List<String> names = List.of("Alice", "Bob", "Charlie", "David");

        // Stream to filter and collect names starting with 'A' or 'D'
        List<String> filteredNames = names.stream()
            .filter(name -> name.startsWith("A") || name.startsWith("D"))
           .collect(Collectors.toList());

        // Print the filtered names
        filteredNames.forEach(System.out::println);
    }
}

💡 Tip: When working with streams, remember that they are lazy and only evaluated when a terminal operation is called. This means you can chain multiple operations without immediate execution, which can lead to more efficient processing.

❓ What is the primary purpose of a lambda expression in Java?

❓ Which of the following is a terminal operation in the Stream API?

← Previous Continue interactively → Next →

Related Courses