0
0
JavaHow-ToBeginner · 3 min read

How to Use Stream Map in Java: Simple Guide with Examples

In Java, stream().map() is used to transform each element in a collection by applying a function. It creates a new stream where each element is the result of the function applied to the original elements.
📐

Syntax

The map method is called on a stream and takes a function as an argument. This function defines how each element is transformed.

  • stream(): Converts a collection into a stream.
  • map(Function): Applies the function to each element.
  • collect(Collectors.toList()): Gathers the results back into a list.
java
collection.stream().map(element -> transformedElement).collect(Collectors.toList());
💻

Example

This example shows how to convert a list of strings to uppercase using map. It demonstrates transforming each element and collecting the results.

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

public class StreamMapExample {
    public static void main(String[] args) {
        List<String> names = List.of("alice", "bob", "charlie");
        List<String> upperNames = names.stream()
            .map(name -> name.toUpperCase())
            .collect(Collectors.toList());
        System.out.println(upperNames);
    }
}
Output
[ALICE, BOB, CHARLIE]
⚠️

Common Pitfalls

One common mistake is forgetting to collect the stream after map, which means no result is produced. Another is using map when you want to filter elements; use filter instead.

Also, map should not modify the original collection elements but return new transformed values.

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

public class StreamMapPitfall {
    public static void main(String[] args) {
        List<String> names = List.of("alice", "bob", "charlie");

        // Wrong: map without collect, no output
        names.stream()
            .map(name -> name.toUpperCase());

        // Right: collect after map
        List<String> upperNames = names.stream()
            .map(name -> name.toUpperCase())
            .collect(Collectors.toList());
        System.out.println(upperNames);
    }
}
Output
[ALICE, BOB, CHARLIE]
📊

Quick Reference

  • stream(): Start a stream from a collection.
  • map(Function): Transform each element.
  • collect(Collectors.toList()): Collect results into a list.
  • filter(Predicate): Use to select elements, not map.

Key Takeaways

Use map to transform each element in a stream with a function.
Always collect the stream after map to get results.
Do not use map to filter elements; use filter instead.
The map function should return new values without modifying originals.
Streams are lazy; operations run only when a terminal method like collect is called.