java stream api

Java Stream API – Complete Guide with All Methods (Interview & Real-World Examples)

Introduction

The Stream API, introduced in Java 8, is one of the most important features for writing clean, functional, and readable code.

Streams allow developers to process collections declaratively instead of using traditional loops.
This article explains almost every important Stream API method, grouped logically, with clear examples—perfect for:

  • Java interviews
  • Daily backend development
  • Spring Boot & Microservices projects

What Is a Stream?

A Stream is not a data structure. It is a sequence of elements supporting:

  • Functional-style operations
  • Lazy evaluation
  • Pipeline processing
list.stream()
    .filter(...)
    .map(...)
    .collect(...);

Stream Lifecycle

  1. Source → Collection / Array / IO
  2. Intermediate Operations → Transformations
  3. Terminal Operation → Result

1️⃣ Stream Creation Methods

stream()

list.stream();

parallelStream()

list.parallelStream();

Stream.of()

Stream.of(1, 2, 3, 4);

Arrays.stream()

Arrays.stream(arr);

2️⃣ Intermediate Operations (Lazy)

filter()

Used to filter elements based on condition.

list.stream()
    .filter(n -> n > 10);

map()

Transforms elements.

list.stream()
    .map(String::toUpperCase);

flatMap()

Flattens nested structures.

listOfLists.stream()
           .flatMap(List::stream)
           .toList();

distinct()

Removes duplicates.

list.stream().distinct();

sorted()

list.stream().sorted();
list.stream().sorted(Comparator.reverseOrder());

peek()

Used mainly for debugging.

list.stream()
    .peek(System.out::println)
    .toList();

limit()

list.stream().limit(5);

skip()

list.stream().skip(2);

3️⃣ Terminal Operations (Trigger Execution)

forEach()

list.stream().forEach(System.out::println);

collect()

Most powerful terminal method.

list.stream().collect(Collectors.toList());

toArray()

Object[] arr = list.stream().toArray();

reduce()

Used for aggregation.

int sum = list.stream()
              .reduce(0, Integer::sum);

min() / max()

list.stream().min(Integer::compareTo);
list.stream().max(Integer::compareTo);

count()

list.stream().count();

findFirst()

list.stream().findFirst();

findAny()

list.stream().findAny();

4️⃣ Matching Operations

anyMatch()

list.stream().anyMatch(n -> n > 50);

allMatch()

list.stream().allMatch(n -> n > 0);

noneMatch()

list.stream().noneMatch(n -> n < 0);

5️⃣ Collectors Utility Methods

groupingBy()

employees.stream()
         .collect(Collectors.groupingBy(Employee::getDept));

counting()

Collectors.counting();

mapping()

Collectors.mapping(Employee::getName, Collectors.toList());

joining()

names.stream()
     .collect(Collectors.joining(", "));

partitioningBy()

numbers.stream()
       .collect(Collectors.partitioningBy(n -> n % 2 == 0));

6️⃣ Primitive Streams

mapToInt(), mapToLong(), mapToDouble()

list.stream()
    .mapToInt(Integer::intValue)
    .sum();

IntStream / LongStream / DoubleStream

IntStream.range(1, 10).forEach(System.out::println);

7️⃣ Parallel Streams

list.parallelStream()
    .filter(n -> n > 10)
    .toList();

Use carefully — not always faster.

8️⃣ Common Interview Questions

❓ Can a Stream be reused?

❌ No — once consumed, it is closed.

❓ Difference between map and flatMap?

  • map → one-to-one
  • flatMap → one-to-many flattening

❓ Are streams lazy?

✅ Yes, intermediate operations execute only when terminal operation is called.

❓ Stream vs Collection

StreamCollection
LazyEager
One-time useReusable
FunctionalImperative

9️⃣ Real-World Use Case

Replacing nested loops:

orders.stream()
      .flatMap(o -> o.getItems().stream())
      .filter(i -> i.getPrice() > 1000)
      .toList();

🔹 Stream Creation Methods

  • stream() – Creates a sequential stream from a collection
  • parallelStream() – Creates a parallel stream for concurrent processing
  • Stream.of() – Creates a stream from given values
  • Arrays.stream() – Creates a stream from an array
  • Stream.generate() – Generates an infinite stream using a supplier
  • Stream.iterate() – Creates an infinite sequential stream with iteration

🔹 Intermediate Operations (Lazy)

  • filter() – Filters elements based on a predicate
  • map() – Transforms each element into another object
  • flatMap() – Flattens nested streams into a single stream
  • distinct() – Removes duplicate elements
  • sorted() – Sorts elements in natural or custom order
  • peek() – Performs an action on elements (mainly for debugging)
  • limit() – Limits the stream to a specified number of elements
  • skip() – Skips the first N elements of the stream

🔹 Terminal Operations (Trigger Execution)

  • forEach() – Performs an action for each element
  • forEachOrdered() – Performs action in encounter order
  • collect() – Converts stream into a collection or custom result
  • toArray() – Converts stream into an array
  • reduce() – Combines elements into a single result
  • min() – Finds the minimum element
  • max() – Finds the maximum element
  • count() – Returns the number of elements
  • findFirst() – Returns the first element
  • findAny() – Returns any element (useful in parallel streams)

🔹 Matching Operations

  • anyMatch() – Checks if any element matches the condition
  • allMatch() – Checks if all elements match the condition
  • noneMatch() – Checks if no elements match the condition

🔹 Collectors Methods

  • Collectors.toList() – Collects elements into a List
  • Collectors.toSet() – Collects elements into a Set
  • Collectors.toMap() – Collects elements into a Map
  • Collectors.groupingBy() – Groups elements by a key
  • Collectors.partitioningBy() – Partitions elements into two groups
  • Collectors.counting() – Counts elements in a stream
  • Collectors.mapping() – Applies mapping before collecting
  • Collectors.joining() – Concatenates strings with delimiter
  • Collectors.summarizingInt() – Returns statistics (count, sum, min, max, avg)

🔹 Primitive Stream Methods

  • mapToInt() – Converts stream to IntStream
  • mapToLong() – Converts stream to LongStream
  • mapToDouble() – Converts stream to DoubleStream
  • IntStream.range() – Generates range excluding end
  • IntStream.rangeClosed() – Generates range including end
  • boxed() – Converts primitive stream to wrapper stream

🔹 Parallel & Utility Methods

  • sequential() – Converts parallel stream to sequential
  • parallel() – Converts sequential stream to parallel
  • unordered() – Removes ordering constraint for optimization
  • onClose() – Registers a close handler for the stream

Top 50 Java Stream API Coding Questions Asked in Interviews

Similar Posts