Java · Lesson 13 of 15
Lambdas and Streams
Functional interfaces, lambdas, method references and the Stream pipeline.
- Intermediate
- 16 min read
- 3 objectives
Before this lessonLesson 12: Generics
What you will learn
- Write lambdas
- Filter, map and collect
- Use Optional safely
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
A lambda is a short anonymous function. It can be used wherever Java expects a functional interface: an interface with a single abstract method, such as Runnable, Comparator or Function.
Lambdas and method references
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Grace", "Al", "Linus"));
names.sort((a, b) -> a.length() - b.length());
System.out.println(names);
names.forEach(System.out::println); // method reference
}
}Output
[Al, Grace, Linus] Al Grace Linus
Stream pipelines
A stream takes data through steps: a source, zero or more intermediate operations (filter, map, sorted) and one terminal operation (collect, count, sum) that actually runs it. The source list is never modified.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
List<Integer> evenSquares = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println(evenSquares);
System.out.println(nums.stream().mapToInt(Integer::intValue).sum());
System.out.println(nums.stream().anyMatch(n -> n > 5));
}
}Output
[4, 16, 36] 21 true
Grouping
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");
Map<Character, List<String>> byLetter = words.stream()
.collect(Collectors.groupingBy(w -> w.charAt(0)));
System.out.println(byLetter);
}
}Output
{a=[apple, avocado], b=[banana, blueberry], c=[cherry]}Optional
Optional<T> makes "there may be no value" explicit, so callers cannot forget the empty case.
import java.util.*;
public class Main {
public static void main(String[] args) {
Optional<String> first = List.of("x", "yy").stream().filter(s -> s.length() > 5).findFirst();
System.out.println(first.orElse("none"));
System.out.println(first.isPresent());
}
}Output
Files and I/ORead and write files with java.nio and handle resources with try-with-resources.
none false
