Thursday, December 11, 2025
HomeLanguagesJavaLongStream mapToObj() in Java

LongStream mapToObj() in Java

LongStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function.

Note : LongStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :

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

Parameters :

  1. U : The element type of the new stream.
  2. Stream : A sequence of elements supporting sequential and parallel aggregate operations.
  3. LongFunction : Represents a function that accepts a long-valued argument and produces a result.
  4. mapper : A stateless function to apply to each element.

Return Value : The function returns an object-valued Stream consisting of the results of applying the given function.

Example 1 :




// Java code for LongStream mapToObj
// (LongFunction mapper)
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.range(3L, 8L);
  
        // Creating a Stream of Strings
        // Using LongStream mapToObj(LongFunction mapper)
        // to store binary representation of
        // elements in LongStream
        Stream<String> stream1 = stream.mapToObj(num
                                                 -> Long.toBinaryString(num));
  
        // Displaying an object-valued Stream
        // consisting of the results of
        // applying the given function.
        stream1.forEach(System.out::println);
    }
}


Output :

11
100
101
110
111

Example 2 :




// Java code for LongStream mapToObj
// (LongFunction mapper)
import java.util.*;
  
import java.math.BigInteger;
import java.util.stream.Stream;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.of(3L, 5L, 7L, 9L, 11L);
  
        // Creating a Stream
        // Using LongStream mapToObj(LongFunction mapper)
        Stream<BigInteger> stream1 = stream
                                         .mapToObj(BigInteger::valueOf);
  
        // Displaying an object-valued Stream
        // consisting of the results of
        // applying the given function.
        stream1.forEach(num -> System.out.println(num.add(BigInteger.TEN)));
    }
}


Output :

13
15
17
19
21
RELATED ARTICLES

Most Popular

Dominic
32443 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11950 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12025 POSTS0 COMMENTS
Shaida Kate Naidoo
6944 POSTS0 COMMENTS
Ted Musemwa
7197 POSTS0 COMMENTS
Thapelo Manthata
6889 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS