LongStream map(LongUnaryOperator mapper) in Java

LongStream map(LongUnaryOperator mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. This is an 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 :

LongStream map(LongUnaryOperator mapper)

Parameters :



  1. LongStream : A sequence of primitive Long-valued elements.
  2. LongUnaryOperator : An operation on a single long-valued operand that produces an long-valued result.
  3. mapper : A stateless function which is applied to each element and the function returns the new stream.

Return Value : LongStream map(LongUnaryOperator mapper) returns a stream by applying the given function.

Example 1 : Using LongStream map() to get the negative of square of elements of LongStream.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream map
// (LongUnaryOperator mapper) to get a
// stream by applying the given function.
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream1 = LongStream.of(4L, 5L, 6L, 7L);
  
        // Using LongStream map()
        LongStream stream2 = stream1.map(num -> (-num * num));
  
        // Displaying the resulting LongStream
        stream2.forEach(System.out::println);
    }
}

chevron_right


Output:

-16
-25
-36
-49

Example 2 :Using LongStream map() to get the half of elements of LongStream in given range.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream map
// (LongUnaryOperator mapper) to get a
// stream by applying the given function.
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream in range [2, 7)
        LongStream stream1 = LongStream.range(2, 7);
  
        // Using LongStream map()
        LongStream stream2 = stream1.map(num -> (num / 2));
  
        // Displaying the resulting LongStream
        stream2.forEach(System.out::println);
    }
}

chevron_right


Output:

1
1
2
2
3


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.