Java Stream Map

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 174 of 306

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 filter or flatMap).
  • The element type can change: a Stream<String> can become a Stream<Integer> or a Stream<Student>. That's what the type parameter R expresses.
  • 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:

  1. Same type, new value: String → uppercased String.
  2. Extracting or computing a value of another type: String → its Integer length.
  3. Building new objects: String → Student. Converting between representations — text to objects, entities to display objects — is one of the most common jobs of map.

Switching between object and primitive streams

MethodFromTo
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)IntStreamIntStream
  • mapToInt(Student::score) gives an IntStream, which offers numeric terminal operations unavailable on Stream<Integer>: sum(), average(), max(), and summaryStatistics(), which computes count, sum, minimum, average and maximum in a single pass.
  • map on an IntStream stays an IntStream (here adding 5 bonus marks, capped at 100); boxed() converts back to Stream<Integer> so it can be collected into a list.
  • mapToObj turns 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]
  • map versus flatMap on 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. Adding distinct().sorted() turns it into a unique, sorted product list.
  • Keeping the parent's data: inside the flatMap lambda, 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::stream turns an empty Optional into an empty stream and a present one into a one-element stream, so flatMap(Optional::stream) keeps only the phone numbers that exist. Ravi has none and simply disappears.
  • mapMulti (Java 16+) is an alternative to flatMap that 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:

  1. flatMap turns 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.
  2. map(String::toLowerCase) normalises case, so "Great" and "great" count as the same word.
  3. Two filters drop very short words (which also removes empty strings) and common "stop words" that carry no meaning.
  4. groupingBy(Function.identity(), counting()) counts each distinct word, producing a Map<String, Long> (Collectors Class lesson).
  5. The map's entries are streamed again and mapped into a WordCount record, which gives the results meaningful names instead of getKey() and getValue().
  6. 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 OrderLine is mapped to a LineDto: 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 map converts each line to its total amount, and reduce(BigDecimal.ZERO, BigDecimal::add) adds them up (Stream Reduce lesson). BigDecimal keeps money exact.
  • GST is 18 % of 1949.00, which is 350.82.
  • The domain objects are unchanged; the mapping is a pure function from Order to InvoiceDto, 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Map and get answers drawn from it.

Signed-in readers only.