Java Stream map() Method
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
// 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.
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().
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.
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);
}
}
[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.
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);
}
}
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.
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);
}
}
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.
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);
}
}
[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; usefilter()orflatMap()for that. - Null results: a mapper may return
null, which then becomes anullelement; 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
| Method | Elements out per element in | Typical use |
|---|---|---|
map(f) | Exactly 1 | Transform 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 primitive | Numeric results without boxing |
peek(c) | The same element | Debugging 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
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:
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);
}
}
map: [[Ana, Ben], [Cy]] flatMap: [Ana, Ben, Cy]
Other mistakes to avoid
- Boxing numbers needlessly:
map(Order::total)followed byreduce()boxes every value; usemapToDouble(). - Huge lambdas: move conversion logic into a named method and use a method reference.
- Mapping to
Optionalby accident: if the mapper returnsOptional, useflatMap(Optional::stream)(Java 9) to unwrap present values.
8. Summary
map()applies aFunctionto each element: one element in, one element out.- It is lazy, stateless and keeps the order and the count.
- Use
mapToInt(),mapToLong()andmapToDouble()for numbers, andmapToObj()to go back to objects. - Use
flatMap()when the function returns a collection or a stream.
9. References
Frequently Asked Questions (FAQ)
Q1. What does map() do in Java streams?
map() is a lazy intermediate operation that applies a Function to every element and returns a stream of the results. Each input element produces exactly one output element, which can be of a different type.
Q2. What is the difference between map() and flatMap()?
map() produces one output per input, so a function returning a list gives a stream of lists. flatMap() expects a function returning a stream and joins all those streams into one flat stream of elements.
Q3. When should I use mapToInt() instead of map()?
Use mapToInt(), mapToLong() or mapToDouble() when the result is a number. They return primitive streams, avoid boxing, and provide sum(), average(), min(), max() and summaryStatistics().
Q4. Does map() change the original collection?
No. It creates new values in a new stream. The source collection is unchanged, unless the mapper itself mutates the elements, which it should not do.
Q5. Can map() return null?
Technically yes; the null becomes an element of the resulting stream. Later operations that call methods on it will fail, so avoid returning null or remove nulls with filter(Objects::nonNull).