LongStream forEach() method in Java

LongStream forEach(LongConsumer action) performs an action for each element of the stream. LongStream forEach(LongConsumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.

Syntax :

void forEach(LongConsumer action)

Parameter : LongConsumer represents an operation that accepts a single long-valued argument and returns no result. This is the primitive type specialization of Consumer for long.



Note : The behavior of this operation is explicitly nondeterministic. Also, for any given element, the action may be performed at whatever time and in whatever thread the library chooses.

Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream forEach
// (LongConsumer action) in Java 8
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.of(7L, 8L, 9L, 10L);
  
        // Using LongStream.forEach
        stream.forEach(System.out::println);
    }
}

chevron_right


Output:

7
8
9
10

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream forEach
// (LongConsumer action) in Java 8
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.range(4L, 9L);
  
        // Using LongStream.forEach() on sequential stream
        stream.forEach(System.out::println);
    }
}

chevron_right


Output:

4
5
6
7
8

Note : For parallel stream, LongStream forEach(LongConsumer action) does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. Below is the example.

Example 3 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream forEach
// (LongConsumer action) in Java 8
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.range(4L, 9L);
  
        // Using LongStream.forEach() on parallel stream
        stream.parallel().forEach(System.out::println);
    }
}

chevron_right


Output:

6
8
7
5
4


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.