00:00

Java Stream map() Method

Last updated:

map() is an intermediate operation of java.util.stream.Stream, available since Java 8, that returns a new stream containing the result of applying a Function to each element. It is a one-to-one transformation: every input element produces exactly one output element, which may be of a different type.

Typical uses are extracting a field, converting entities to DTOs, formatting values and calculating derived numbers. This tutorial covers map() and its primitive variants mapToInt(), mapToLong(), mapToDouble() and mapToObj(), and compares it with flatMap().

1. Syntax and Method Signatures

Stream.java (API)
// java.util.stream.Stream<T> (Java 8)
<R> Stream<R>  map(Function<? super T, ? extends R> mapper)
IntStream      mapToInt(ToIntFunction<? super T> mapper)
LongStream     mapToLong(ToLongFunction<? super T> mapper)
DoubleStream   mapToDouble(ToDoubleFunction<? super T> mapper)

// java.util.stream.IntStream (Java 8)
IntStream      map(IntUnaryOperator mapper)
<U> Stream<U>  mapToObj(IntFunction<? extends U> mapper)

T is the input element type and R the output type. The mapper is a Function<? super T, ? extends R> with the method R apply(T t). The result is a Stream<R> with the same number of elements, in the same order.

Usage
List<String> names = employees.stream()
        .map(Employee::name)       // Stream<Employee> -> Stream<String>
        .toList();

2. How map() Works

For each element pulled by the terminal operation, map() calls mapper.apply(element) and passes the result on. It is stateless, lazy and order-preserving, and it never drops or adds elements. Because the count does not change, a sized stream stays sized after map(), which is why count() can sometimes skip the mapper entirely.

When the result is a number, prefer mapToInt(), mapToLong() or mapToDouble(). They return primitive streams that avoid boxing and give you sum(), average() and max().

map() applies a function to every element Three Employee objects, Asha with salary 52000, Ravi with 61000 and Lena with 48000, pass through map with the function Employee::name. The result is a stream of three strings: Asha, Ravi and Lena, in the same order. EMPLOYEE Asha, 52000 Ravi, 61000 Lena, 48000 map(Employee::name) STRING "Asha" "Ravi" "Lena"
Figure 1: Each element is replaced by the function's result. The count and the order stay the same; the element type can change, here from Employee to String.

3. Java Examples

Example 1: Transforming strings (Java 9+)

Turn product codes typed by users into a normalised form: trimmed and upper case.

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

public class NormaliseCodes {

    public static void main(String[] args) {
        List<String> typed = List.of("  sku-101", "Sku-205 ", "sKU-330");

        List<String> codes = typed.stream()
                .map(String::trim)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        System.out.println(codes);
    }
}
Output
[SKU-101, SKU-205, SKU-330]

How it works: Each map() applies one transformation. Chaining two small maps reads better than one lambda doing both, and the cost is the same.

Example 2: Entities to DTOs (Java 16+)

An API must return customers without their internal fields. Convert each Customer into a CustomerView.

CustomerToView.java
import java.util.List;

public class CustomerToView {

    record Customer(long id, String firstName, String lastName, String passwordHash, String city) { }

    record CustomerView(String fullName, String city) { }

    static CustomerView toView(Customer c) {
        return new CustomerView(c.firstName() + " " + c.lastName(), c.city());
    }

    public static void main(String[] args) {
        List<Customer> customers = List.of(
                new Customer(1, "Rhea", "Kapoor", "x9f..", "Indore"),
                new Customer(2, "Sam", "Fernandes", "a1c..", "Panaji"));

        List<CustomerView> views = customers.stream()
                .map(CustomerToView::toView)
                .toList();

        views.forEach(System.out::println);
    }
}
Output
CustomerView[fullName=Rhea Kapoor, city=Indore]
CustomerView[fullName=Sam Fernandes, city=Panaji]

How it works: A named method, toView(), holds the conversion, and map() applies it through a method reference. The password hash never reaches the view objects.

Example 3: Mapping to numbers with mapToDouble (Java 16+)

Compute the total value of an order, where each line has a quantity, a unit price and a discount percentage.

OrderLineTotals.java
import java.util.List;

public class OrderLineTotals {

    record Line(String item, int qty, double price, int discountPercent) {
        double total() {
            return qty * price * (100 - discountPercent) / 100.0;
        }
    }

    public static void main(String[] args) {
        List<Line> lines = List.of(
                new Line("Keyboard", 2, 1500.0, 10),
                new Line("Mouse", 3, 400.0, 0),
                new Line("Monitor", 1, 12000.0, 5));

        double orderTotal = lines.stream()
                .mapToDouble(Line::total)
                .sum();

        System.out.printf("Order total: %.2f%n", orderTotal);
    }
}
Output
Order total: 15300.00

How it works: mapToDouble() turns each line into a double and returns a DoubleStream, whose sum() adds them. With plain map() you would get a Stream<Double> and need a collector to sum it. For real money, prefer BigDecimal or whole paise.

Example 4: From numbers back to objects with mapToObj

Generate seat labels A1 to A5 from an IntStream of seat numbers.

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

public class SeatLabels {

    public static void main(String[] args) {
        List<String> labels = IntStream.rangeClosed(1, 5)
                .mapToObj(n -> "A" + n)
                .collect(Collectors.toList());

        int doubledSum = IntStream.rangeClosed(1, 5).map(n -> n * 2).sum();

        System.out.println(labels);
        System.out.println("Sum of doubled seat numbers: " + doubledSum);
    }
}
Output
[A1, A2, A3, A4, A5]
Sum of doubled seat numbers: 30

How it works: On an IntStream, map() must return an int; to produce objects, use mapToObj(), which returns a Stream<U>.

4. Real-World Use Cases

  • API layers: map entities to DTOs or JSON views before returning them.
  • Data import: map CSV lines to domain objects with a parsing method.
  • Reporting: map orders to amounts with mapToDouble() and total them.
  • Formatting: map dates, prices or names into display strings.

5. Important Points

  • One in, one out: map() never changes the number of elements; use filter() or flatMap() for that.
  • Null results: a mapper may return null, which then becomes a null element; avoid it or filter afterwards.
  • Do not mutate the input inside the mapper; create and return a new value instead.
  • Exceptions in the mapper stop the whole pipeline; checked exceptions must be wrapped.
  • Primitive variants avoid boxing and should be used for numeric results.

6. map() vs Related Methods

MethodElements out per element inTypical use
map(f)Exactly 1Transform or extract a value
flatMap(f)0 or more (a stream)Flatten nested collections
mapMulti(f)0 or more (pushed to a consumer)Small expansions without creating streams (Java 16)
mapToInt(f) etc.Exactly 1 primitiveNumeric results without boxing
peek(c)The same elementDebugging only, no transformation

See flatMap() for nested data and mapMulti() for the Java 16 alternative.

7. Common Mistakes and Best Practices

Using map() for side effects

Wrong
users.stream().map(u -> { emailService.send(u); return u; }).count();   // the mapper may never run

Since Java 9, count() may skip map() because it cannot change the size. Use forEach() for actions.

Getting a Stream of a Stream

If the mapper returns a collection or a stream, map() wraps it instead of flattening it:

MapVsFlatMapResult.java
import java.util.List;

public class MapVsFlatMapResult {

    record Team(String name, List<String> members) { }

    public static void main(String[] args) {
        List<Team> teams = List.of(new Team("Blue", List.of("Ana", "Ben")), new Team("Red", List.of("Cy")));

        List<List<String>> nested = teams.stream().map(Team::members).toList();
        List<String> flat = teams.stream().flatMap(t -> t.members().stream()).toList();

        System.out.println("map:     " + nested);
        System.out.println("flatMap: " + flat);
    }
}
Output
map:     [[Ana, Ben], [Cy]]
flatMap: [Ana, Ben, Cy]

Other mistakes to avoid

  • Boxing numbers needlessly: map(Order::total) followed by reduce() boxes every value; use mapToDouble().
  • Huge lambdas: move conversion logic into a named method and use a method reference.
  • Mapping to Optional by accident: if the mapper returns Optional, use flatMap(Optional::stream) (Java 9) to unwrap present values.

8. Summary

  • map() applies a Function to each element: one element in, one element out.
  • It is lazy, stateless and keeps the order and the count.
  • Use mapToInt(), mapToLong() and mapToDouble() for numbers, and mapToObj() to go back to objects.
  • Use flatMap() when the function returns a collection or a stream.

9. References