Java Stream Map
The map Operation
map transforms each element of a stream into a new value:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
- The mapper function is applied to every element; the stream that comes out contains the results, in the same order.
- The number of elements stays the same — one result per input (to change the count, use
filterorflatMap). - The element type can change: a
Stream<String>can become aStream<Integer>or aStream<Student>. That's what the type parameterRexpresses. - Like
filter, it's a lazy, stateless intermediate operation.
map is the workhorse of stream pipelines: extracting a field, converting units, formatting values for display, turning database entities into API objects. This lesson covers map, its primitive variants, and flatMap for one-to-many transformations.
Transforming Elements
import java.util.*;
import java.util.stream.*;
public class M1 {
record Student(String name, int score) { }
public static void main(String[] args) {
List<String> names = List.of("asha", "ravi", "meena");
System.out.println(names.stream().map(String::toUpperCase).toList());
System.out.println(names.stream().map(String::length).toList());
System.out.println(names.stream().map(n -> new Student(n, n.length() * 20)).toList());
List<Student> students = List.of(new Student("Asha", 91), new Student("Ravi", 45), new Student("Meena", 77));
IntSummaryStatistics stats = students.stream().mapToInt(Student::score).summaryStatistics();
System.out.println(stats);
System.out.println(students.stream().mapToInt(Student::score).map(s -> Math.min(100, s + 5)).boxed().toList());
System.out.println(IntStream.rangeClosed(1, 3).mapToObj(i -> "Lesson " + i).toList());
System.out.println(students.stream().mapToDouble(s -> s.score() / 10.0).sum());
}
}
Output:
[ASHA, RAVI, MEENA]
[4, 4, 5]
[Student[name=asha, score=80], Student[name=ravi, score=80], Student[name=meena, score=100]]
IntSummaryStatistics{count=3, sum=213, min=45, average=71.000000, max=91}
[96, 50, 82]
[Lesson 1, Lesson 2, Lesson 3]
21.3
The first three lines show the three typical uses:
- Same type, new value:
String→ uppercasedString. - Extracting or computing a value of another type:
String→ itsIntegerlength. - Building new objects:
String→Student. Converting between representations — text to objects, entities to display objects — is one of the most common jobs ofmap.
Switching between object and primitive streams
| Method | From | To |
|---|---|---|
mapToInt(ToIntFunction) | Stream<T> | IntStream |
mapToLong(ToLongFunction) | Stream<T> | LongStream |
mapToDouble(ToDoubleFunction) | Stream<T> | DoubleStream |
mapToObj(IntFunction) | IntStream (etc.) | Stream<R> |
boxed() | IntStream (etc.) | Stream<Integer> (etc.) |
map(IntUnaryOperator) | IntStream | IntStream |
mapToInt(Student::score)gives anIntStream, which offers numeric terminal operations unavailable onStream<Integer>:sum(),average(),max(), andsummaryStatistics(), which computes count, sum, minimum, average and maximum in a single pass.mapon anIntStreamstays anIntStream(here adding 5 bonus marks, capped at 100);boxed()converts back toStream<Integer>so it can be collected into a list.mapToObjturns numbers into objects — the usual way to generate labels or records from an index range.mapToDouble(...).sum()adds 9.1 + 4.5 + 7.7 = 21.3.
Using primitive streams for arithmetic avoids creating an Integer or Double object for every element.
flatMap: One Element to Many
Sometimes each element produces several results — an order has several items, a line has several words, a customer may or may not have a phone number. map would produce a stream of collections; flatMap flattens them into one stream:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
The mapper returns a stream for each element, and flatMap concatenates all those streams.
import java.util.*;
import java.util.stream.*;
public class Flat {
record Order(String id, List<String> items) { }
public static void main(String[] args) {
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(), List.of(4, 5, 6));
System.out.println("map: " + nested.stream().map(List::size).toList());
System.out.println("flatMap: " + nested.stream().flatMap(List::stream).toList());
List<Order> orders = List.of(new Order("O-1", List.of("pen", "ink")), new Order("O-2", List.of("bag", "pen")));
System.out.println("all items: " + orders.stream().flatMap(o -> o.items().stream()).toList());
System.out.println("unique items: " + orders.stream().flatMap(o -> o.items().stream()).distinct().sorted().toList());
System.out.println("pairs: " + orders.stream()
.flatMap(o -> o.items().stream().map(item -> o.id() + ":" + item)).toList());
List<String> lines = List.of("streams are lazy", "streams are not collections");
System.out.println(lines.stream().flatMap(l -> Arrays.stream(l.split(" "))).distinct().toList());
Map<String, String> phoneOf = Map.of("Asha", "+91-90000-11111", "Meena", "+91-90000-33333");
List<String> phones = Stream.of("Asha", "Ravi", "Meena")
.map(name -> Optional.ofNullable(phoneOf.get(name)))
.flatMap(Optional::stream)
.toList();
System.out.println(phones);
System.out.println(Stream.of("a,b", "c").<String>mapMulti((s, out) -> {
for (String part : s.split(",")) out.accept(part.toUpperCase());
}).toList());
}
}
Output:
map: [2, 1, 0, 3]
flatMap: [1, 2, 3, 4, 5, 6]
all items: [pen, ink, bag, pen]
unique items: [bag, ink, pen]
pairs: [O-1:pen, O-1:ink, O-2:bag, O-2:pen]
[streams, are, lazy, not, collections]
[+91-90000-11111, +91-90000-33333]
[A, B, C]
mapversusflatMapon a list of lists:map(List::size)gives one result per inner list (4 results);flatMap(List::stream)streams each inner list and joins them, giving the 6 numbers. The empty list contributes nothing.- Navigating relationships:
orders.stream().flatMap(o -> o.items().stream())lists every item from every order. Addingdistinct().sorted()turns it into a unique, sorted product list. - Keeping the parent's data: inside the
flatMaplambda, the inner stream can be mapped while the outer element (o) is still in scope, producing "order:item" pairs. - Splitting text: each line becomes a stream of words, and all the words form one stream.
- Skipping missing values:
Optional::streamturns an emptyOptionalinto an empty stream and a present one into a one-element stream, soflatMap(Optional::stream)keeps only the phone numbers that exist. Ravi has none and simply disappears. mapMulti(Java 16+) is an alternative toflatMapthat pushes results to a consumer instead of returning a stream. It's often more efficient when each element produces only a few results, because no intermediate stream objects are created.
map versus peek
peek(action) runs an action on each element and passes the same element along unchanged. It's intended for debugging (as in the Stream API lesson). Don't use peek to modify elements or to perform the pipeline's real work: stream implementations are allowed to skip peek actions when they can compute the result without visiting elements (for example, list.stream().peek(...).count() may never run the action). Use map when you transform values.
Practical Example: Word Frequencies from Reviews
Counting the most frequent meaningful words in customer reviews shows flatMap and map working together with filtering, grouping and sorting.
import java.util.*;
import java.util.function.Function;
import java.util.stream.*;
public class Words {
record WordCount(String word, long count) { }
static final Set<String> STOP = Set.of("a", "an", "the", "is", "are", "to", "of", "and", "in", "it", "you");
public static void main(String[] args) {
String reviews = """
The Java course is great. Streams and lambdas are explained clearly!
Great examples; the streams section is the best part of the course.
Clear, practical, and great value. Java streams finally make sense to me.
""";
List<WordCount> top = reviews.lines()
.flatMap(line -> Arrays.stream(line.split("[^\\p{L}]+")))
.map(String::toLowerCase)
.filter(w -> w.length() > 2)
.filter(w -> !STOP.contains(w))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.map(e -> new WordCount(e.getKey(), e.getValue()))
.sorted(Comparator.comparingLong(WordCount::count).reversed().thenComparing(WordCount::word))
.limit(5)
.toList();
top.forEach(w -> System.out.printf("%-8s %s%n", w.word(), "#".repeat((int) w.count())));
}
}
Output:
great ###
streams ###
course ##
java ##
best #
Step by step:
flatMapturns the stream of lines into a stream of words. The regular expression[^\p{L}]+splits on any run of characters that aren't letters, so punctuation (.,;,!,,) is removed and works for letters in any language.map(String::toLowerCase)normalises case, so "Great" and "great" count as the same word.- Two filters drop very short words (which also removes empty strings) and common "stop words" that carry no meaning.
groupingBy(Function.identity(), counting())counts each distinct word, producing aMap<String, Long>(Collectors Class lesson).- The map's entries are streamed again and mapped into a
WordCountrecord, which gives the results meaningful names instead ofgetKey()andgetValue(). - Sorting: by count descending, then alphabetically for ties, so the output is stable.
limit(5)keeps the top five, and each count is drawn as a small text bar.
Practical Example: Converting Entities to DTOs
Applications rarely send their internal objects directly to a client. They map them into DTOs (data transfer objects) shaped for the response — formatted, flattened and with computed fields.
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class Dto {
record Product(String sku, String name, BigDecimal price) { }
record OrderLine(Product product, int qty) { }
record Order(String id, String customer, List<OrderLine> lines) { }
record LineDto(String description, int qty, String unitPrice, String total) { }
record InvoiceDto(String orderId, String customer, List<LineDto> lines, String subtotal, String gst, String grandTotal) { }
static String money(BigDecimal v) { return "Rs " + v.setScale(2, RoundingMode.HALF_UP).toPlainString(); }
static InvoiceDto toInvoice(Order order) {
List<LineDto> lines = order.lines().stream()
.map(l -> new LineDto(
l.product().name() + " (" + l.product().sku() + ")",
l.qty(),
money(l.product().price()),
money(l.product().price().multiply(BigDecimal.valueOf(l.qty())))))
.toList();
BigDecimal subtotal = order.lines().stream()
.map(l -> l.product().price().multiply(BigDecimal.valueOf(l.qty())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal gst = subtotal.multiply(new BigDecimal("0.18"));
return new InvoiceDto(order.id(), order.customer(), lines, money(subtotal), money(gst), money(subtotal.add(gst)));
}
public static void main(String[] args) {
Product pen = new Product("PEN-01", "Gel pen", new BigDecimal("12.50"));
Product bag = new Product("BAG-07", "Laptop bag", new BigDecimal("1899"));
Order order = new Order("O-1001", "Asha Rao", List.of(new OrderLine(pen, 4), new OrderLine(bag, 1)));
InvoiceDto inv = toInvoice(order);
System.out.println("Invoice " + inv.orderId() + " for " + inv.customer());
inv.lines().forEach(l -> System.out.printf(" %-24s x%d %10s %12s%n", l.description(), l.qty(), l.unitPrice(), l.total()));
System.out.printf(" %-38s %12s%n %-38s %12s%n %-38s %12s%n",
"Subtotal", inv.subtotal(), "GST 18%", inv.gst(), "Total", inv.grandTotal());
}
}
Output:
Invoice O-1001 for Asha Rao
Gel pen (PEN-01) x4 Rs 12.50 Rs 50.00
Laptop bag (BAG-07) x1 Rs 1899.00 Rs 1899.00
Subtotal Rs 1949.00
GST 18% Rs 350.82
Total Rs 2299.82
- Each
OrderLineis mapped to aLineDto: the nested product is flattened into one description, prices are formatted, and the line total is computed. The DTO contains exactly what an invoice page or PDF needs. - A second
mapconverts each line to its total amount, andreduce(BigDecimal.ZERO, BigDecimal::add)adds them up (Stream Reduce lesson).BigDecimalkeeps money exact. - GST is 18 % of 1949.00, which is 350.82.
- The domain objects are unchanged; the mapping is a pure function from
OrdertoInvoiceDto, which makes it easy to test.
In web applications, mapping code like toInvoice sits between the service layer and the controller, often generated by libraries such as MapStruct — but stream().map(...) is what it amounts to.