JLambda Expressions and Stream API

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use two of the most important features of Java 8 - Lambda expressions and Stream API. Lambda expressions are used to create anonymous functions that can be passed as arguments to other methods, whereas Stream API is used to perform a sequence of operations on a collection.

Set up the Java environment

First, set up the Java environment by installing the latest version of Java on your system. You can download and install Java from the official website. After installation, open the terminal and check the version of Java.

java -version

Create a Java file

Next, create a new Java file in your ~/project directory named LambdaExpressions.java.

touch ~/project/LambdaExpressions.java

In this file, we will write code to implement the Lambda expressions and Stream API.

Use a Lambda expression to calculate the sum of two numbers

Lambda expressions provide an easy way to create anonymous functions. Create a FunctionalInterface that will represent a function that takes two numbers as input and returns their sum.

interface Calculator {
  int sum(int a, int b);
}

Next, we can use the Lambda expression to create an object of this interface and then call the sum() function using that object.

  Calculator adder = (a, b) -> a + b;
  int result = adder.sum(10, 20);
  System.out.println("Result: " + result);

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

Result: 30

Iterate over a collection using Stream API

Stream API is used to perform a sequence of operations on a collection. In this step, we will learn how to iterate over a collection of strings and filter out strings that start with "A".

Create a list of strings containing a few names to work with.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave", "Andy");

Next, use the Stream API to iterate over this collection, filter out strings that start with "A", and print the remaining ones to the console.

  names.stream().filter(s -> s.startsWith("A")).forEach(System.out::println);

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

Alice
Andy

Use Stream API to find maximum and minimum from a list of integers

Stream API provides a way to perform a sequence of operations on a collection. In this step, we will learn how to use Stream API to find the maximum and minimum elements from a list of integers.

Create a list of integers

List<Integer> numbers = Arrays.asList(10, 2, 30, 5, 4, 20);

Find the maximum element of the list using Stream API.

Optional<Integer> maxNum = numbers.stream().max(Integer::compareTo);
System.out.println("Maximum number: " + maxNum.get());

Find the minimum element of the list using Stream API.

Optional<Integer> minNum = numbers.stream().min(Integer::compareTo);
System.out.println("Minimum number: " + minNum.get());

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

Maximum number: 30
Minimum number: 2

Use forEach() to print the elements of a list

We can use the forEach() method of the Stream API to iterate over a list and perform an action on each element.

Create a list of strings containing a few names to work with.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");

Print all elements of the list using the forEach() method.

names.stream().forEach(System.out::println);

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

Alice
Bob
Charlie
Dave

Use Stream API to sort a Collection

Stream API can be used to sort a collection. In this step, we will learn how to sort a list of integers in ascending order.

Create a list of integers to work with.

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

Sort the list in ascending order using the sorted() method of the Stream API.

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

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

1
2
3
4
5

Use Stream API to filter and sort a collection

In this step, we will use Stream API to filter and sort a collection of integers.

Create a list of integers to work with.

List<Integer> numbers = Arrays.asList(10, 2, 30, 5, 4, 20);

Filter out only the even numbers and sort them in descending order using the sorted() method.

numbers.stream().filter(n -> n % 2 == 0).sorted(Comparator.reverseOrder()).forEach(System.out::println);

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

30
20
10
4
2

Use Stream API to get the average of a collection

In this step, we will learn how to use Stream API to get the average of a collection of integers.

Create a list of integers to work with.

List<Integer> numbers = Arrays.asList(10, 2, 30, 5, 4, 20);

Use the average() method of the Stream API to get the average of the list.

OptionalDouble avg = numbers.stream().mapToInt(Integer::intValue).average();
System.out.println("Average: " + avg.getAsDouble());

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

Average: 12.0

Create an Optional object and check if it's empty or not

In this step, we will learn what Optional is and how to create an Optional object.

Create an Optional object of an empty string.

Optional<String> emptyString = Optional.empty();

Check if this object is empty using the isPresent() method.

if(emptyString.isPresent()) {
    System.out.println(emptyString.get());
}
else {
    System.out.println("No value");
}

Now, compile and run this code using the following command:

javac ~/project/LambdaExpressions.java && java LambdaExpressions

The output should be:

No value

Summary

In this lab, we learned how to use two of the most important features of Java 8 - Lambda expressions and Stream API. We learned how to use Lambda expressions to create anonymous functions, how to use the Stream API to perform a sequence of operations on a collection, and how to create Optional objects and check if they are empty or not. We also saw how to use Stream API to sort, filter, and get the average of a collection. By mastering these features, we can write efficient and clean code using Java 8.

Other Java Tutorials you may like