A lambda expression is a short way of writing a function that is passed as data – for example, a rule for comparing or a condition for filtering. The Stream API uses lambdas so that processing a collection can be written as a series of steps: select, calculate, sort, add up. This style is used a lot in Spring Boot applications.
Before you start: what you need to know first – lists, maps and sets, interfaces. How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.
A lambda expression
A lambda has parameters, an arrow -> and a body: x -> x * x is a function that returns the square. The type of a lambda is a functional interface – an interface with one abstract method:
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x; // input -> output
Predicate<String> isLong = s -> s.length() > 5; // input -> true/false
BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;
Runnable greeting = () -> System.out.println("Hello!"); // no parameters
System.out.println(square.apply(7));
System.out.println(isLong.test("Java") + " " + isLong.test("Programming"));
System.out.println(sum.apply(3, 4));
greeting.run();
// a lambda with several statements: curly brackets and return
Function<Integer, String> describe = n -> {
if (n % 2 == 0) return n + " is even";
return n + " is odd";
};
System.out.println(describe.apply(15));
}
}
Output:
49
false true
7
Hello!
15 is odd
Interface
Method
Example
Function<T, R>
R apply(T t)
s -> s.length()
Predicate<T>
boolean test(T t)
x -> x > 0
Consumer<T>
void accept(T t)
x -> System.out.println(x)
Supplier<T>
T get()
() -> new ArrayList<>()
Comparator<T>
int compare(T a, T b)
(a, b) -> a - b
Method references
When a lambda only calls an existing method, you can write it more briefly as Class::method:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("mark", "Ana", "iva", "Luke"));
names.sort(String::compareToIgnoreCase); // (a, b) -> a.compareToIgnoreCase(b)
names.forEach(System.out::println); // x -> System.out.println(x)
names.replaceAll(String::toUpperCase); // s -> s.toUpperCase()
System.out.println(names);
}
}
Output:
Ana
iva
Luke
mark
[ANA, IVA, LUKE, MARK]
Stream: filter, map, sorted, collect
A stream is a sequence of data through which the elements "flow" through processing steps. The steps are chained with a dot, and at the end there is a terminal operation (collect, count, sum, forEach…):
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = List.of(7, 2, 9, 4, 12, 5, 8, 3);
List<Integer> squaresOfEven = numbers.stream()
.filter(x -> x % 2 == 0) // keep the even ones: 2, 4, 12, 8
.map(x -> x * x) // square them: 4, 16, 144, 64
.sorted() // sort
.collect(Collectors.toList());
System.out.println(squaresOfEven);
long greaterThan5 = numbers.stream().filter(x -> x > 5).count();
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
double average = numbers.stream().mapToInt(x -> x).average().orElse(0);
int max = numbers.stream().max(Integer::compare).get();
System.out.println(greaterThan5 + " " + sum + " " + average + " " + max);
String joined = numbers.stream().limit(3).map(String::valueOf).collect(Collectors.joining(" + "));
System.out.println(joined);
}
}
Output:
[4, 16, 64, 144]
4 50 6.25 12
7 + 2 + 9
A stream does not change the original list – it makes a new result. One stream can be used only once.
A stream over a list of objects
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
record Product(String name, String category, double price) { }
public static void main(String[] args) {
List<Product> p = List.of(
new Product("Notebook", "school", 120),
new Product("Pencil", "school", 45),
new Product("Ball", "sport", 1500),
new Product("Backpack", "school", 2900),
new Product("Racket", "sport", 3200));
// names of products cheaper than 2000, sorted by price
List<String> cheap = p.stream()
.filter(x -> x.price() < 2000)
.sorted(Comparator.comparingDouble(Product::price))
.map(Product::name)
.toList();
System.out.println(cheap);
// total price by category
Map<String, Double> byCategory = p.stream()
.collect(Collectors.groupingBy(Product::category, TreeMap::new,
Collectors.summingDouble(Product::price)));
System.out.println(byCategory);
// the most expensive product
p.stream().max(Comparator.comparingDouble(Product::price))
.ifPresent(x -> System.out.println("Most expensive: " + x.name()));
}
}
Output:
[Pencil, Notebook, Ball]
{school=3065.0, sport=4700.0}
Most expensive: Racket
max returns an Optional – a "box" that may be empty (if the list is empty). ifPresent runs the code only if a value exists.
When a stream, and when a loop?
A stream is clear for selecting, calculating and grouping data. An ordinary loop is clearer when you use an index, when you stop early (break) or when you change several variables at once. In competitions loops are used most often (they are faster to write and to run), and in applications (Spring Boot) – streams.
Practice tasks
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: medium
Word statistics
Read one line of text. Using a stream, print: the number of words, the number of different words (regardless of upper and lower case), and the words longer than 4 letters, in lower case, without repetition, in alphabetical order, separated by commas.
Example
Input
Java is a language and Java runs on every computer language
Output
11
9
computer, every, language
Hint
Arrays.stream(line.toLowerCase().split("\\s+")), then count(), distinct().count() and filter(...).distinct().sorted().collect(Collectors.joining(", ")).
Solution (Java)
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String line = new Scanner(System.in).nextLine().trim().toLowerCase();
String[] words = line.split("\\s+");
System.out.println(words.length);
System.out.println(Arrays.stream(words).distinct().count());
System.out.println(Arrays.stream(words)
.filter(w -> w.length() > 4)
.distinct()
.sorted()
.collect(Collectors.joining(", ")));
}
}
TASK 02Difficulty: harder
The best in each grade
Read n, then the name, grade and number of points of each student. For each grade (in ascending order) print grade: name points of the student with the most points; if there are several, the first one alphabetically.
Example
Input
6
Ana 7 88
Mark 8 91
Iva 7 95
Luke 8 91
Sara 6 70
Nina 7 95
Output
6: Sara 70
7: Iva 95
8: Luke 91
Hint
Collectors.groupingBy(Student::grade, TreeMap::new, Collectors.minBy(order)), where order puts more points first, and then the name alphabetically.
Solution (Java)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
record Student(String name, int grade, int points) { }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Student> s = new ArrayList<>();
for (int i = 0; i < n; i++)
s.add(new Student(sc.next(), sc.nextInt(), sc.nextInt()));
Comparator<Student> order = Comparator.comparingInt(Student::points).reversed()
.thenComparing(Student::name);
Map<Integer, Optional<Student>> best = s.stream()
.collect(Collectors.groupingBy(Student::grade, TreeMap::new, Collectors.minBy(order)));
best.forEach((grade, x) ->
System.out.println(grade + ": " + x.get().name() + " " + x.get().points()));
}
}
Common mistakes and tips
A lambda can use a local variable from its surroundings only if that variable is not changed afterwards (effectively final).
A stream cannot be used twice – for another processing make a new one with list.stream().
map changes every element, filter removes elements – do not mix them up.
Do not change the list a stream reads from inside forEach.
Check your knowledge
Open the quiz
Lambdas and streams
1. What does x -> x * 2 do?
2. Which operation keeps only the elements that meet a condition?
3. What is String::length?
4. Does a stream change the original list?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.