ZetCode

Java Stream mapToObj

last modified May 25, 2025

This article explores the Java Stream mapToObj method, which enables the conversion of primitive streams (IntStream, LongStream, DoubleStream) into object streams. By transforming numerical data into reference types, mapToObj enhances flexibility in stream operations, making it easier to apply complex transformations and object manipulations.

The mapToObj method is an intermediate stream operation designed specifically for primitive streams. It converts each primitive value into an object, enabling seamless transitions between primitive and reference-based data structures. This method is the counterpart to mapToInt, mapToLong, and mapToDouble, ensuring compatibility across different data representations in Java's functional programming paradigm.

Using mapToObj, developers can leverage object-oriented features such as storing additional metadata, applying complex logic to individual elements, and integrating primitive values into more structured models. This makes it a valuable tool for efficiently processing numerical data while maintaining the advantages of Java Streams.

Basic mapToObj syntax

The mapToObj method allows you to convert each primitive value in a stream to an object, enabling flexible data transformations between primitive and object streams.

// IntStream
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)

// LongStream
<U> Stream<U> mapToObj(LongFunction<? extends U> mapper)

// DoubleStream
<U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper)

The mapper function converts each primitive value to an object of type U.

Converting numbers to strings

You can easily convert a stream of primitive numbers to a stream of strings by mapping each number to a descriptive string representation.

Main.java
void main() {

    IntStream.rangeClosed(1, 5)
             .mapToObj(i -> "Number " + i)
             .forEach(System.out::println);
}

This example converts a range of integers to descriptive strings. The lambda i -> "Number " + i serves as the mapping function.

$ java Main.java
Number 1
Number 2
Number 3
Number 4
Number 5

Creating custom objects

Primitive values can be mapped to custom objects, allowing you to build more complex data structures directly from primitive streams.

Main.java
record Square(int side, int area) {}

void main() {

    IntStream.rangeClosed(1, 5)
             .mapToObj(side -> new Square(side, side * side))
             .forEach(System.out::println);
}

This example creates Square objects from integer values, calculating the area as part of the mapping process.

$ java Main.java
Square[side=1, area=1]
Square[side=2, area=4]
Square[side=3, area=9]
Square[side=4, area=16]
Square[side=5, area=25]

Combining with other operations

The mapToObj method can be used in combination with other stream operations to create powerful and expressive data processing pipelines.

Main.java
void main() {

    IntStream.range(0, 100)
             .filter(n -> n % 15 == 0)
             .mapToObj(n -> n + " is divisible by 15")
             .limit(5)
             .forEach(System.out::println);
}

This example filters numbers divisible by 15, converts them to descriptive strings, limits to 5 results, and prints them.

$ java Main.java
0 is divisible by 15
15 is divisible by 15
30 is divisible by 15
45 is divisible by 15
60 is divisible by 15

Working with DoubleStream

You can use mapToObj on a DoubleStream to convert double values into formatted strings or other object types as needed.

Main.java
void main() {

    DoubleStream.of(1.5, 2.3, 3.7, 4.1)
               .mapToObj(d -> String.format("Value: %.2f", d))
               .forEach(System.out::println);
}

This example formats double values to strings with 2 decimal places using mapToObj on a DoubleStream.

$ java Main.java
Value: 1.50
Value: 2.30
Value: 3.70
Value: 4.10

Boxing primitive values

Primitive values can be boxed into their corresponding wrapper classes, such as converting an IntStream to a Stream of Integer objects.

Main.java
void main() {

    List<Integer> numbers = IntStream.rangeClosed(1, 5)
                                   .mapToObj(Integer::valueOf) // can be replaced with boxed()
                                   .toList();
    
    System.out.println("Collected numbers: " + numbers);
}

This example converts an IntStream to a List<Integer> by boxing each primitive int to an Integer object.

$ java Main.java
Collected numbers: [1, 2, 3, 4, 5]

Building complex objects

You can create complex object hierarchies from primitive values by mapping each value to a new instance of a custom class.

Main.java
class Circle {
    double radius;
    double area;
    
    Circle(double radius) {
        this.radius = radius;
        this.area = Math.PI * radius * radius;
    }
    
    @Override public String toString() {
        return String.format("Circle[r=%.1f, a=%.2f]", radius, area);
    }
}

void main() {

    IntStream.rangeClosed(1, 5)
             .mapToObj(Circle::new)
             .forEach(System.out::println);
}

This example creates Circle objects with calculated areas from integer radii.

$ java Main.java
Circle[r=1.0, a=3.14]
Circle[r=2.0, a=12.57]
Circle[r=3.0, a=28.27]
Circle[r=4.0, a=50.27]
Circle[r=5.0, a=78.54]

Combining with flatMap

By combining mapToObj with flatMap, you can perform advanced transformations and flatten nested streams into a single stream of objects.

Main.java
void main() {

    IntStream.rangeClosed(1, 3)
             .mapToObj(i -> IntStream.rangeClosed(1, i)
                                    .mapToObj(j -> i + "x" + j + "=" + (i*j)))
             .flatMap(s -> s)
             .forEach(System.out::println);
}

This example generates a multiplication table by first creating streams of strings for each number and then flattening them into a single stream.

$ java Main.java
1x1=1
2x1=2
2x2=4
3x1=3
3x2=6
3x3=9

Source

Java Stream mapToObj documentation

In this article we have explored the Java Stream mapToObj method. It serves as a bridge between primitive streams and object streams, enabling flexible data transformations while maintaining stream processing efficiency.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Java tutorials.