Lambdas, the Stream API and Optional in tests
A lambda is a short implementation of a functional interface, one with a single abstract method. A Stream is a lazy, single-use pipeline: intermediate operations only describe the plan and a terminal operation runs it. allMatch on an empty stream returns true, so an "all elements" check must also confirm that elements exist. Optional.orElse always evaluates its argument, while orElseGet calls the Supplier only when the value is absent.
Java · Lambdas and Streams
The check "all buttons are disabled" is green although there are no buttons on the page at all. Why?
A test checks that in "read only" mode all buttons are disabled: buttons.stream().allMatch(b -> !b.isEnabled()). After a markup change the locator stopped finding buttons, the list is empty, and the check stayed green. allMatch on an empty stream returns true: there was nothing to violate the condition. Streams and Optional have several such surprises, and all of them are silent.
This lesson covers what a lambda is, how a stream pipeline works (laziness, terminal operations, single use), where Optional helps tests and which places break checks most often.
How it works and why it is designed so
A lambda is a short way to write an implementation of a functional interface, that is, an interface with one abstract method. The compiler itself picks which interface the code means from the place the lambda is passed to. So in tests we see it wherever a method accepts such an interface.
| Interface | What it does | Where you meet it |
|---|---|---|
Predicate<T> | takes a value, returns boolean | filter, removeIf, anyMatch |
Function<T,R> | transforms a value | map, WebDriverWait.until |
Consumer<T> | takes, returns nothing | forEach, ifPresent |
Supplier<T> | takes nothing, returns a value | orElseGet, orElseThrow |
Comparator<T> | compares two values | sorted, Comparator.comparing |
Runnable, Callable<V> | an action with no arguments | threads, ExecutorService.submit |
Executable (JUnit) | an action with no arguments that may throw any exception | assertThrows, assertAll |
A method reference shortens a lambda that only calls another method: WebElement::getText instead of e -> e.getText(). A lambda sees only effectively final local variables (those that are not reassigned), so a counter cannot be changed inside: use count(), AtomicInteger or turn the stream into a collect instead.
Selenium waits also accept a lambda: until takes a Function, so wait.until(d -> d.findElement(By.id("ready")).isDisplayed()) works. until repeats the function until it returns a value other than null and false, or the time runs out.
A Stream is a pipeline: a source (list.stream()), then intermediate operations (filter, map, sorted, distinct) and one terminal operation (toList, collect, count, anyMatch, findFirst, forEach). Intermediate operations are lazy: they only describe a plan and execute nothing until the terminal operation starts the computation. Elements go through the pipeline one by one, and short-circuiting operations (findFirst, anyMatch, limit) stop the pass as soon as the answer is known. A stream can be used once: a second use throws IllegalStateException.
A stream pipeline
Example: a loop and a stream, and the empty list trap
We collect the visible non-empty texts of table rows. The stream reads as a description of the result:
List<String> titles = rows.stream()
.filter(WebElement::isDisplayed)
.map(WebElement::getText)
.map(String::strip)
.filter(text -> !text.isEmpty())
.toList(); // Java 16+, an unmodifiable list
Now the buttons. allMatch on an empty stream gives true, anyMatch gives false and noneMatch gives true. So a check on all elements is always paired with a check that the elements exist:
List<WebElement> buttons = driver.findElements(By.cssSelector("button.action"));
// before: an empty list passes too
assertTrue(buttons.stream().allMatch(b -> !b.isEnabled()));
// after: first "there is something to check", then the condition
assertThat(buttons).isNotEmpty();
assertThat(buttons).allSatisfy(b -> assertThat(b.isEnabled()).isFalse());
The second advantage of allSatisfy: on failure AssertJ shows which element failed, while allMatch returns just false. A sortedness check without copying the list:
List<Integer> prices = page.prices();
boolean ascending = IntStream.range(1, prices.size())
.allMatch(i -> prices.get(i - 1) <= prices.get(i));
assertTrue(ascending, "prices are not sorted: " + prices);
For a list of zero or one element the range is empty, so the result is true, which is formally correct, but here too it is worth checking that the list is not empty.
Collectors. Collectors.groupingBy groups elements by a key, Collectors.joining(", ") builds a string for a message. Collectors.toMap throws IllegalStateException on a duplicate key unless you pass a merge function: a useful signal that the test data has duplicates.
Map<Role, List<User>> byRole = users.stream().collect(Collectors.groupingBy(User::role));
Map<String, User> byEmail = users.stream()
.collect(Collectors.toMap(User::email, Function.identity())); // duplicate email = exception
Optional is a "the value may be absent" container for a method result, such as findFirst. Useful ways to unwrap it:
User admin = users.stream()
.filter(u -> u.role() == Role.ADMIN)
.findFirst()
.orElseThrow(() -> new AssertionError("No admin in test data"));
String name = maybeName.orElse("anonymous"); // a default value
User created = existing.orElseGet(() -> api.createUser()); // creates only when needed
maybeName.ifPresentOrElse(n -> log.info(n), () -> log.warn("no name"));
The difference between orElse and orElseGet matters: the argument of orElse(api.createUser()) is evaluated always, even when the value is present, and an extra user will be created in the system. orElseGet takes a Supplier and calls it only when the value is absent. get() without a check throws NoSuchElementException with no explanation, so orElseThrow with a message is better. Do not make Optional a class field or a method parameter: it is meant for returned results.
Limits and alternatives. A stream is not always more readable. If a chain is longer than five or six operations or contains a multi-line nested lambda, extract the logic into a named method or go back to a loop: in a loop it is easier to set a breakpoint and see which element failed. Do not use parallelStream() in tests with a shared driver or state: it runs work in a shared thread pool, and WebDriver is not thread-safe. Do not change an outer list from inside map or forEach (side effects in a stream): collect and toList exist for gathering. A lambda in map or filter cannot throw a checked exception (Function and Predicate do not declare one), so it is wrapped (UncheckedIOException) or the loop is extracted.
Common mistakes
allMatchwithout checking that elements exist: an empty list makes the test green.orElse(expensiveCall())instead oforElseGet: the side effects run every time.- Reusing a stream:
IllegalStateException: stream has already been operated upon or closed. forEachthat appends to an outer list instead ofcollect;peekleft in code not for debugging.toMapwithout a merge function on data with duplicates, andOptional.get()without a check.
Check yourself
What does Collections.emptyList().stream().allMatch(x -> false) return and why does it matter for tests?
Answer
true: an empty stream has no element that violates the condition. So an "all elements…" check without checking that elements exist passes when a locator found nothing.
A user is already in the Optional. How does existing.orElse(api.createUser()) differ from existing.orElseGet(() -> api.createUser())?
Answer
In the first, createUser() is always called, before orElse even runs, so an extra user is created. In the second the Supplier runs only when the value is absent.
In Stream<String> s = names.stream().filter(n -> check(n)); the method check prints nothing although it contains a log call. Why?
Answer
Intermediate operations are lazy: filter only describes a plan. Without a terminal operation (toList, count, findFirst…) the lambda is never executed.
filter and map are intermediate operations, toList and count are terminal. Optional returns a result that may be absent, and I get the value out through orElseThrow with a message. Middle/Senior: I know a stream is lazy and single-use and that allMatch on an empty collection is true, so I first check that elements exist. I tell orElse and orElseGet apart by side effects. I do not use parallelStream with a shared driver, I extract long chains into methods or go back to a loop, and for detailed failure messages I take allSatisfy from AssertJ.