Lambdas and Streams
A lambda is a short anonymous function: (a, b) -> a + b. Streams process collections in a pipeline of steps such as filter, map, sorted and collect, ending with an operation like sum, count or forEach.
Example
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 2, 8, 1, 9, 4);
List<Integer> evens = nums.stream().filter(n -> n % 2 == 0).sorted().collect(Collectors.toList());
System.out.println(evens);
System.out.println(nums.stream().mapToInt(n -> n).sum());
nums.stream().map(n -> n * 10).limit(3).forEach(System.out::println);
}
}Result
[2, 4, 8] 29 50 20 80
Exercise
The arrow in a lambda is...
(a, b) a + b
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.