LongStream forEach() method in Java
Last Updated :
06 Dec, 2018
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 :
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(7L, 8L, 9L, 10L);
stream.forEach(System.out::println);
}
}
|
Example 2 :
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.range(4L, 9L);
stream.forEach(System.out::println);
}
}
|
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 :
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.range(4L, 9L);
stream.parallel().forEach(System.out::println);
}
}
|
Share your thoughts in the comments
Please Login to comment...