Lesson 32 of 34 · Collections & Exceptions
Java Lambdas and Streams Basics
So far you have processed lists with loops: create a result list, loop, check a condition, add. Modern Java (since Java 8) offers a shorter, more declarative style: you pass small pieces of behaviour — lambdas — to methods, and you describe what should happen to a collection with streams.
Lambdas
A lambda is an anonymous function written inline: parameters, an arrow, and a body.
x -> x * 2 // one parameter
(a, b) -> a + b // two parameters
name -> { // a block body needs return
String trimmed = name.trim();
return trimmed.toUpperCase();
}
A lambda can be used wherever Java expects a functional interface — an interface with exactly one abstract method. java.util.function has ready-made ones:
Predicate<String> isLong = s -> s.length() > 5; // test(...) → boolean
Function<String, Integer> size = s -> s.length(); // apply(...) → a result
Consumer<String> shout = s -> System.out.println(s + "!"); // accept(...)
Supplier<List<String>> fresh = () -> new ArrayList<>(); // get()
System.out.println(isLong.test("Highlands")); // true
System.out.println(size.apply("Java")); // 4
When a lambda only calls an existing method, a method reference is even shorter: String::length, String::toUpperCase, System.out::println.
Lambdas with collections
Many collection methods take lambdas directly:
List<String> heroes = new ArrayList<>(List.of("Ola", "Bartholomew", "Ari"));
heroes.removeIf(h -> h.length() > 5); // drop long names
heroes.sort(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()));
heroes.forEach(System.out::println);
Ari
Ola
Streams
A stream is a pipeline that data flows through. It has three parts: a source, any number of intermediate operations, and one terminal operation that produces the result:
List<Integer> scores = List.of(42, 7, 99, 15, 64);
List<Integer> top = scores.stream() // source
.filter(s -> s >= 40) // keep 42, 99, 64
.sorted(Comparator.reverseOrder()) // 99, 64, 42
.toList(); // terminal → [99, 64, 42]
int total = scores.stream().mapToInt(Integer::intValue).sum(); // 227
String text = scores.stream().map(String::valueOf).collect(Collectors.joining(", "));
Common building blocks:
- Intermediate:
filter,map,sorted,distinct,limit - Terminal:
toList(),collect(...),count(),forEach(...),anyMatch(...) - Numbers:
mapToInt(...)gives anIntStreamwithsum(),max()andaverage();average()returns anOptionalDouble, so finish with.orElse(0.0)for empty input.
Streams are lazy — nothing happens until the terminal operation runs — and they never change the source list. A stream can be used only once.
Common mistakes
- Forgetting the terminal operation:
names.stream().filter(...)alone does nothing. - Changing local variables in a lambda:
count++inside a lambda does not compile — captured local variables must be effectively final. Let the stream compute the value (count(),sum()). - Adding to a
toList()result: the list returned bystream().toList()is unmodifiable. Copy it intonew ArrayList<>(...)if you need to change it.
Assignment
Implement four static methods in Main, each with a stream pipeline:
shortNamesUpper(List<String> names, int maxLength)returns the names with at mostmaxLengthcharacters, in uppercase, in their original order.shortNamesUpper(List.of("Ann", "Bartholomew", "Cy"), 3)→[ANN, CY]sumOfSquaresOfEvens(List<Integer> numbers)returns the sum of the squares of the even numbers.sumOfSquaresOfEvens(List.of(1, 2, 3, 4))→20(4 + 16)sortedByLength(List<String> words)returns a new list sorted by length, with words of equal length in alphabetical order. The input list must not change.sortedByLength(List.of("pear", "fig", "banana", "kiwi"))→[fig, kiwi, pear, banana]averageLength(List<String> words)returns the average word length as adouble, or0.0for an empty list.averageLength(List.of("a", "abc"))→2.0
Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Transforming collections in other languages
- JavaScript Array map, filter and reduce · JavaScript
- Python List Comprehensions · Python
- LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate · C#
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .