CodeGym /Courses /JAVA 25 SELF /Basic Stream API operations: map, filter, collect

Basic Stream API operations: map, filter, collect

JAVA 25 SELF
Level 30, Lesson 1
Available

1. Creating a stream

To use the Stream API, you first need to get a stream from some collection or array.

Examples of creating a stream

// From a list
List<String> names = List.of("Anna", "Boris", "Alex", "Alina");
Stream<String> stream = names.stream();

// From an array
int[] numbers = {1, 2, 3, 4, 5};
IntStream intStream = Arrays.stream(numbers);

// From individual values
Stream<String> letters = Stream.of("A", "B", "C");

In short:

  • list.stream() — for collections
  • Arrays.stream(array) — for arrays
  • Stream.of(...) — for individual values

Example in the context of our application

Suppose we have a list of users:

List<String> users = List.of("Ivan", "Anna", "Petr", "Alexey");
Stream<String> userStream = users.stream();

Intermediate and terminal operations

An important point: operations in the Stream API fall into two types.

  • Intermediate operations (for example, filter, map, distinct) — describe processing stages. They return a new stream but do not trigger anything by themselves.
  • Terminal operations (for example, collect, forEach, count) — start the pipeline and yield a result.

A stream is “lazy”: until a terminal operation is called, no computation happens. That’s why we often end a chain with collect(...) — this is the point where the stream turns back into a collection or another result.

2. Operation filter: filtering elements by condition

filter is an intermediate operation that lets through only those elements that match a given condition.

Signature

Stream<T> filter(Predicate<? super T> predicate); 

Predicate is a functional interface that takes an element and returns true (keep) or false (discard).

Example: keep only even numbers

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

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

System.out.println(evenNumbers); // [2, 4, 6]

What happens?

  • n -> n % 2 == 0 — a lambda expression that checks whether the number is divisible by 2 without remainder.
  • filter keeps only even numbers.

Example: filter names that start with “A”

List<String> names = List.of("Anna", "Boris", "Alex", "Alina", "Ivan");

List<String> aNames = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());

System.out.println(aNames); // [Anna, Alex, Alina]

Important: filter does not modify the collection — it creates a new stream that contains only the needed elements.

3. Operation map: turning an element into something else

map is a transformation operation. It takes each element of the stream, applies a function to it, and returns a new element.

Signature

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

Function is an interface that takes an element and returns something (possibly of another type).

Example: get string lengths

List<String> names = List.of("Anna", "Boris", "Alex");

List<Integer> nameLengths = names.stream()
    .map(name -> name.length())
    .collect(Collectors.toList());

System.out.println(nameLengths); // [4, 5, 4]

What happens?

  • map turns a string into its length (name -> name.length()).
  • As a result, you get a stream of numbers.

Example: convert strings to upper case

List<String> names = List.of("Anna", "Boris", "Alex");

List<String> upperNames = names.stream()
    .map(name -> name.toUpperCase())
    .collect(Collectors.toList());

System.out.println(upperNames); // [ANNA, BORIS, ALEX]

4. Operation collect: gathering the result back into a collection

collect is a terminal operation, meaning it ends the stream’s work and assembles the result into a collection or another container.

Signature

<R, A> R collect(Collector<? super T, A, R> collector)

Don’t be scared by the scary signature! In 99% of cases, you’ll use the ready-made collectors from the Collectors class.

Collectors is a utility class with a set of “collectors.” It tells the stream what form to assemble the result into: a list, a set, a string, and so on.

Examples:

  • Collectors.toList() — into a List
  • Collectors.toSet() — into a Set
  • Collectors.joining(", ") — into a string separated by commas

Think of Collectors as a set of boxes of different shapes that you use to pack stream elements.

Example: collect the result into a List

List<String> filtered = names.stream()
    .filter(name -> name.length() > 3)
    .collect(Collectors.toList());

Example: collect the result into a Set

Set<String> uniqueNames = names.stream()
    .map(String::toLowerCase)
    .collect(Collectors.toSet());

Example: collect strings separated by commas

String result = names.stream()
    .collect(Collectors.joining(", "));

System.out.println(result); // Anna, Boris, Alex

5. Operation chaining: filtering + transforming + collecting the result

The biggest strength of the Stream API is the ability to chain operations one after another.

Example: get the lengths of names starting with “A”

List<String> names = List.of("Anna", "Boris", "Alex", "Alina", "Ivan");

List<Integer> aNameLengths = names.stream()
    .filter(name -> name.startsWith("A"))
    .map(String::length)
    .collect(Collectors.toList());

System.out.println(aNameLengths); // [4, 4, 5]

Step by step:

  1. .stream() — create a stream from the list.
  2. .filter(name -> name.startsWith("A")) — keep only names that start with "A".
  3. .map(String::length) — turn each name into its length.
  4. .collect(Collectors.toList()) — collect the result into a list.

Equivalent imperative code

Here’s what the same thing would look like the “old-fashioned” way:

List<Integer> result = new ArrayList<>();
for (String name : names) {
    if (name.startsWith("A")) {
        result.add(name.length());
    }
}

Compare: Stream API — one line; it reads like “what we do,” not “how we do it.”

6. Practice: a few short exercises

Let’s practice! You can run all the examples in a single file — just change the data.

Task 1: Keep only odd numbers and square them

List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);

List<Integer> oddSquares = numbers.stream()
    .filter(n -> n % 2 != 0)
    .map(n -> n * n)
    .collect(Collectors.toList());

System.out.println(oddSquares); // [1, 9, 25, 49]

Task 2: From a list of strings, get a list of their first letters

List<String> names = List.of("Anna", "Boris", "Alex");

List<Character> initials = names.stream()
    .map(name -> name.charAt(0))
    .collect(Collectors.toList());

System.out.println(initials); // [A, B, A]

Task 3: Filter strings longer than 3 and collect them into a Set

List<String> words = List.of("cat", "dog", "elephant", "ant", "bear");

Set<String> longWords = words.stream()
    .filter(word -> word.length() > 3)
    .collect(Collectors.toSet());

System.out.println(longWords); // [bear, elephant]

7. Common mistakes when working with filter, map, collect

Error No. 1: forgot collect — no result!
The Stream API is lazy, like a cat on a windowsill: until you call a terminal operation (for example, collect or forEach), nothing will happen. If you write only users.stream().filter(...).map(...); — it performs no actions.

Error No. 2: filter and map are swapped
Sometimes beginners apply map first and then filter. For example, names.stream().map(String::length).filter(len -> len > 3) yields numbers, not strings. If you need strings longer than 3, filter first, transform afterwards.

Error No. 3: forgot about immutability
Stream API operations do not change the original collection! They return a new result. After List<String> upper = names.stream().map(String::toUpperCase).collect(Collectors.toList()); — the names collection remains the same.

Error No. 4: trying to use an external mutable list
Don’t do this:

List<String> result = new ArrayList<>();
names.stream().filter(...).forEach(name -> result.add(name));

It’s better to use collect — it’s safer and shorter.

Error No. 5: NullPointerException
If the collection may contain null elements, calling name.startsWith("A") on null will throw an error. Add a null filter if that’s possible:

.filter(name -> name != null && name.startsWith("A"))
1
Task
JAVA 25 SELF, level 30, lesson 1
Locked
Inventory in the Magic Shop 🍎
Inventory in the Magic Shop 🍎
1
Task
JAVA 25 SELF, level 30, lesson 1
Locked
Sensor Monitoring in the Laboratory 🧪
Sensor Monitoring in the Laboratory 🧪
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION