Tuesday, July 28, 2026
HomeLanguagesJavaDoubleStream forEach() method in Java

DoubleStream forEach() method in Java

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

Syntax :

void forEach(DoubleConsumer action)

Parameter :

  1. DoubleConsumer : Represents an operation that accepts a single double-valued argument and returns no result. This is the primitive type specialization of Consumer for double.

Note : The behaviour 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 :




// Java code for DoubleStream forEach
// (DoubleConsumer action) in Java 8
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream
        DoubleStream stream = DoubleStream.of(7.3, 8.2, 9.5, 10.6);
  
        // Using DoubleStream.forEach
        stream.forEach(System.out::println);
    }
}


Output:

7.3
8.2
9.5
10.6

Note : For parallel stream, DoubleStream forEach(DoubleConsumer 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 2 :




// Java code for DoubleStream forEach
// (DoubleConsumer action) in Java 8
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an DoubleStream
        DoubleStream stream = DoubleStream.of(7.3, 8.2, 9.5, 10.6);
  
        // Using DoubleStream.forEach() on parallel stream
        stream.parallel().forEach(System.out::println);
    }
}


Output:

9.5
7.3
8.2
10.6
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6903 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6972 POSTS0 COMMENTS