#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Core Java

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

  1. Source: where elements come from, such as list.stream(), Arrays.stream(array) or Stream.of(...).
  2. Intermediate operations: steps like filter, map, sorted and distinct. They are lazy, meaning nothing happens until the pipeline ends.
  3. Terminal operation: the step that produces a result, such as collect, count, forEach or anyMatch. 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

OperationPurposeTesting example
mapTransform each elementTurn user objects into email strings
allMatchTrue if every element passesEvery price in a response is positive
anyMatch / noneMatchCheck existence or absenceNo product has an empty name
distinct + countFind duplicatesOrder IDs are unique
sortedOrder elementsCompare with UI sort order
Collectors.groupingByGroup into a mapCount users per role
Collectors.joiningBuild one stringReadable 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 filter and map does nothing at all.
  • Side effects inside map. Adding to outside lists from within a lambda is error-prone, especially with parallel streams; use collect.
  • Calling get() on an empty Optional. Prefer orElse, orElseThrow with a clear message, or isPresent checks.
  • Modifying a toList() result. It is unmodifiable; use Collectors.toList() or copy into a new ArrayList if 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.

Explore Course