how to use findFirst in IntStream?

Here is an example to explain how to use findFirst in IntStream.

Syntax:

Modifier and Type                Method
OptionalInt                      findFirst()
package com.nourit.java8.Streams.IntStream;

import java.util.OptionalInt;
import java.util.stream.IntStream;

public class IntStreamFindFirst {

  public static void main(String[] args) {
    // Returns an OptionalInt describing the first element of this stream,
    // or
    // an empty OptionalInt if the stream is empty.
    IntStream i0 = IntStream.of(11, 12, 13, 14, 5, 6, 7, 8);
    System.out.println("---------- FindFirst Example 1 -----------------");
    OptionalInt n0 = i0.findFirst();
    if (n0.isPresent()) {
      System.out.println(n0.getAsInt());
    } else {
      System.out.println("Is Empty");
    }
    // Returns an OptionalInt describing the first element of this stream,
    // or
    // an empty OptionalInt if the stream is empty.
    IntStream i1 = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8);
    System.out.println("---------- FindFirst Example 2 -----------------");
    OptionalInt n = i1.findFirst();
    if (n.isPresent()) {
      System.out.println(n.getAsInt());
    } else {
      System.out.println("Is Empty");
    }
    System.out.println("---------- FindFirst Example 3 -----------------");
    // Returns an OptionalInt describing the first element of this stream,
    // or
    // an empty OptionalInt if the stream is empty.
    IntStream emptyStream = IntStream.empty();
    OptionalInt on = emptyStream.findFirst();
    if (on.isPresent()) {
      System.out.println(on.getAsInt());
    } else {
      System.out.println("Is Empty");
    }
    System.out.println("---------------------------------------");
  }
}

Output:

---------- FindAny Example 1 -----------------
11
---------- FindAny Example 1 -----------------
1
---------- FindAny Example 2 -----------------
Is Empty
---------------------------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*