Skip to main content

Command Palette

Search for a command to run...

Streams and Lambda Expressions

Published
2 min readView as Markdown
Streams and Lambda Expressions
E

I am a passionate software engineer in training at ALX. I have a strong preference for back-end development. I am on course to share my learning journey with you.

Introduction

In the previous lesson, we explored Threads and Concurrency, which enable multitasking and efficient CPU utilization. Now, we move on to Java Streams and Lambda Expressions, which introduce functional programming concepts to Java, making data processing more concise and readable.

Functional Programming Introduction

Functional programming in Java emphasizes writing code in a declarative style. Lambda expressions allow concise function definitions, making Java code more readable and maintainable.

Example: Lambda Expression

interface MathOperation {
    int operate(int a, int b);
}

public class LambdaExample {
    public static void main(String[] args) {
        MathOperation addition = (a, b) -> a + b;
        System.out.println("Sum: " + addition.operate(5, 3));
    }
}

/*
* Output:
* Sum: 8
*/

Streams API Overview

The Streams API simplifies data processing using a functional approach. It supports operations like filtering, mapping, and reducing collections efficiently.

Example: Using Streams to Filter Data

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

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Kwame", "Yaw", "Abena", "Esi");
        List<String> filteredNames = names.stream()
                                          .filter(name -> name.startsWith("A"))
                                          .collect(Collectors.toList());
        System.out.println(filteredNames);
    }
}

/*
* Output:
* [Abena]
* 
*/

Common Stream Operations

  • map(): Transforms elements

  • filter(): Selects matching elements

  • reduce(): Aggregates elements

  • sorted(): Sorts the elements

Example: Mapping and Reducing

import java.util.*;

public class StreamMapReduce {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.stream().map(n -> n * 2).reduce(0, Integer::sum);
        System.out.println("Sum of doubled numbers: " + sum);
    }
}

/*
* Output:
* Sum of doubled numbers: 30
*
*/

Conclusion

Java Streams and Lambda Expressions bring the power of functional programming to Java, enabling cleaner, more readable, and efficient code. Mastering these concepts will greatly enhance your ability to process data concisely and effectively.

Stay tuned for the next topic in the Java Short Notes series!