DoubleStream findFirst() method in Java


The findFirst() method returns an OptionalDouble describing the first element of this stream. It returns an empty OptionalDouble if the stream is empty.

The syntax is as follows

OptionalDouble findFirst()

Here, OptionalDouble is a container object which may or may not contain a double value.

To use the DoubleStream class in Java, import the following package

import java.util.stream.DoubleStream;

First, create a DoubleStream with some elements

DoubleStream doubleStream = DoubleStream.of(15.6, 30.2, 50.5, 78.9, 80.4, 95.8);

Now, get the first element of this stream using the findFirst() method

OptionalDouble res = doubleStream.findFirst();

The following is an example to implement DoubleStream findFirst() method in Java

Example

 Live Demo

import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.of(15.6, 30.2, 50.5, 78.9, 80.4, 95.8);
      OptionalDouble res = doubleStream.findFirst();
      System.out.println("The first element of the stream = ");
      if (res.isPresent())
         System.out.println(res.getAsDouble());
      else
         System.out.println("Nothing!");
   }
}

Output

The first element of the stream =
15.6

Example

 Live Demo

import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.empty();
      OptionalDouble res = doubleStream.findFirst();
      if (res.isPresent())
         System.out.println(res.getAsDouble());
      else
         System.out.println("Nothing! Stream is empty!");
   }
}

Here is the output displaying the else condition since the stream is empty

Output

Nothing! Stream is empty!

Updated on: 30-Jul-2019

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements