Java Stream API
100%

Java Stream API

The Java Stream API, introduced in Java 8, provides a way to process collections of data using operations such as filtering, mapping, sorting, and reducing.

Streams help you write cleaner code when working with lists, sets, and other data sources. A stream processes data; it does not store the data itself.

1. What Is the Stream API?

A stream is a sequence of elements that supports operations to process data. A typical stream pipeline contains:

  • Source: The collection or data source.
  • Intermediate operations: Operations such as filter() and map().
  • Terminal operation: An operation such as forEach() or collect() that produces a result or performs an action.
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(10, 20, 30, 40);

        numbers.stream()
               .forEach(System.out::println);
    }
}
Output:
10
20
30
40
2. Creating a Stream

You can create a stream from a collection using stream().

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List names =
            Arrays.asList("Amit", "Rahul", "Priya");

        Stream stream = names.stream();

        stream.forEach(System.out::println);
    }
}
Output:
Amit
Rahul
Priya

You can also create a stream directly using Stream.of().

Stream.of("Java", "Python", "C++")
      .forEach(System.out::println);
3. Using filter()

The filter() method selects elements that satisfy a condition.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(10, 15, 20, 25, 30);

        numbers.stream()
               .filter(n -> n > 20)
               .forEach(System.out::println);
    }
}
Output:
25
30

Only numbers greater than 20 pass through the filter.

4. Using map()

The map() method transforms each element into another value.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(1, 2, 3, 4, 5);

        numbers.stream()
               .map(n -> n * n)
               .forEach(System.out::println);
    }
}
Output:
1
4
9
16
25

Each number is multiplied by itself before being printed.

5. Using sorted()

The sorted() method sorts stream elements in their natural order.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(50, 10, 40, 20, 30);

        numbers.stream()
               .sorted()
               .forEach(System.out::println);
    }
}
Output:
10
20
30
40
50

For numbers, natural order means ascending order. For strings, it generally means lexicographical order.

6. Using distinct()

The distinct() method removes duplicate elements from a stream according to their equality.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(10, 20, 10, 30, 20, 40);

        numbers.stream()
               .distinct()
               .forEach(System.out::println);
    }
}
Output:
10
20
30
40

In this example, each distinct number is printed once.

7. Using limit() and skip()

The limit() method keeps at most a specified number of elements. The skip() method skips the first specified number of elements.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(10, 20, 30, 40, 50);

        System.out.println("Limit:");

        numbers.stream()
               .limit(3)
               .forEach(System.out::println);

        System.out.println("Skip:");

        numbers.stream()
               .skip(2)
               .forEach(System.out::println);
    }
}
Output:
Limit:
10
20
30
Skip:
30
40
50
8. Using count()

The count() method returns the number of elements in a stream.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List names =
            Arrays.asList("Amit", "Rahul", "Priya", "Neha");

        long total = names.stream().count();

        System.out.println("Total Names: " + total);
    }
}
Output:
Total Names: 4

The return type of count() is long.

9. Using reduce()

The reduce() method combines stream elements into a single result. For example, it can calculate a sum.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(10, 20, 30, 40);

        int sum = numbers.stream()
                         .reduce(0, (a, b) -> a + b);

        System.out.println("Sum: " + sum);
    }
}
Output:
Sum: 100

The initial value is 0. Each element is combined with the accumulated result.

10. Collecting Stream Results into a List

Use collect() with Collectors.toList() to gather stream results into a list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(1, 2, 3, 4, 5, 6);

        List evenNumbers = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());

        System.out.println(evenNumbers);
    }
}
Output:
[2, 4, 6]

The filtered elements are collected into a new list. The original list is not changed by this pipeline.

11. Using anyMatch(), allMatch(), and noneMatch()

These methods check whether elements satisfy a condition. Each returns a boolean result.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(2, 4, 6, 8);

        System.out.println(
            numbers.stream().anyMatch(n -> n > 5)
        );

        System.out.println(
            numbers.stream().allMatch(n -> n % 2 == 0)
        );

        System.out.println(
            numbers.stream().noneMatch(n -> n < 0)
        );
    }
}
Output:
true
true
true
  • anyMatch() returns true if at least one element matches.
  • allMatch() returns true if every element matches.
  • noneMatch() returns true if no element matches.
12. Combining Stream Operations

You can combine several stream operations into one pipeline to filter, transform, sort, and display data.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers =
            Arrays.asList(5, 12, 8, 20, 3, 16);

        numbers.stream()
               .filter(n -> n > 7)
               .map(n -> n * 2)
               .sorted()
               .forEach(System.out::println);
    }
}
Output:
16
24
32
40

How it works:

  1. filter() keeps numbers greater than 7: 12, 8, 20, 16.
  2. map() doubles them: 24, 16, 40, 32.
  3. sorted() sorts them: 16, 24, 32, 40.
  4. forEach() prints each result.
13. Important Stream API Rules
  • Streams do not store elements; they process data from a source.
  • Intermediate operations such as filter() and map() are generally lazy.
  • A terminal operation such as forEach(), count(), or collect() triggers pipeline processing.
  • A stream should not be reused after a terminal operation has consumed it.
  • Stream operations usually do not modify the original collection unless your own code explicitly changes it.
  • Use stream() for sequential processing and consider parallelStream() only when parallel processing is appropriate.
Java Stream API Assignments
  1. Create a list of numbers and print all elements using a stream.
  2. Filter a list to display only even numbers.
  3. Use map() to calculate the square of each number.
  4. Sort a list of names alphabetically.
  5. Remove duplicate values using distinct().
  6. Display the first three elements using limit().
  7. Count the number of names in a list.
  8. Calculate the sum of numbers using reduce().
  9. Collect all numbers greater than 50 into a new list.
  10. Use anyMatch() to check whether a list contains a number greater than 100.
  11. Filter names that start with the letter A.
  12. Combine filter(), map(), and sorted() in one pipeline.

Quick Quiz: Java Stream API

Select the correct answer for each question.

1. Which method filters stream elements using a condition?



2. Which method counts stream elements?



3. Which method combines stream elements into one result?