Java Streams
What is a Stream?
Introduced in Java 8, a Stream is a sequence of elements that supports functional-style operations — filtering, mapping, and reducing — without modifying the original data source.
Example
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
Why Testers Use Streams
Streams make it concise to filter or transform data extracted from a response — for example, pulling out all "active" user IDs from a list of user objects returned by an API.
The Three Parts of Every Stream Pipeline
- Source: where elements come from, such as
list.stream(),Arrays.stream(array)orStream.of(...). - Intermediate operations: steps like
filter,map,sortedanddistinct. They are lazy, meaning nothing happens until the pipeline ends. - Terminal operation: the step that produces a result, such as
collect,count,forEachoranyMatch. Only now does data flow through.
Laziness lets Java stop early. With findFirst(), elements after the first match are never processed. Streams also never change the source collection; filtering a list of users produces a new result while the original list stays exactly as the API returned it, which is helpful when several assertions need the same data.
Operations Testers Use Most
| Operation | Purpose | Testing example |
|---|---|---|
map | Transform each element | Turn user objects into email strings |
allMatch | True if every element passes | Every price in a response is positive |
anyMatch / noneMatch | Check existence or absence | No product has an empty name |
distinct + count | Find duplicates | Order IDs are unique |
sorted | Order elements | Compare with UI sort order |
Collectors.groupingBy | Group into a map | Count users per role |
Collectors.joining | Build one string | Readable failure messages |
Worked Example: Validating an API Response
An endpoint returns a list of users, each with id, email, role and active. After deserialising into a List<User>, streams make the checks short:
List<User> users = response.jsonPath().getList("data", User.class);
List<Integer> activeIds = users.stream()
.filter(User::isActive)
.map(User::getId)
.sorted()
.toList(); // Java 16+, unmodifiable result
boolean allEmailsValid = users.stream()
.allMatch(u -> u.getEmail() != null && u.getEmail().contains("@"));
Assert.assertTrue(allEmailsValid, "Every user should have a valid email");
long uniqueIds = users.stream().map(User::getId).distinct().count();
Assert.assertEquals(uniqueIds, users.size(), "User IDs must be unique");
Map<String, Long> perRole = users.stream()
.collect(Collectors.groupingBy(User::getRole, Collectors.counting()));
Optional<User> admin = users.stream()
.filter(u -> "admin".equals(u.getRole()))
.findFirst();
Assert.assertTrue(admin.isPresent(), "At least one admin expected");
The same style works in Selenium: driver.findElements(By.cssSelector(".price")).stream().map(WebElement::getText).toList() collects every visible price for comparison.
Pitfalls to Watch For
- Reusing a stream. A stream can be consumed once; calling a second terminal operation throws
IllegalStateException. Create a new stream from the list instead. - Forgetting the terminal step. A pipeline with only
filterandmapdoes nothing at all. - Side effects inside
map. Adding to outside lists from within a lambda is error-prone, especially with parallel streams; usecollect. - Calling
get()on an emptyOptional. PreferorElse,orElseThrowwith a clear message, orisPresentchecks. - Modifying a
toList()result. It is unmodifiable; useCollectors.toList()or copy into a newArrayListif you must change it. - Overusing streams. A plain loop is often clearer for logic with many branches or early exits.
Ready to master real-world software testing?
Learn manual and automation testing hands-on with mentor-led sessions.