How to use findAny in IntStream?

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

Syntax:

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

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

public class IntStreamFindAny {

  public static void main(String[] args) {
    // Returns an OptionalInt describing some element of the 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("---------- FindAny Example 1 -----------------");
    OptionalInt n = i1.findAny();
    if (n.isPresent()) {
      System.out.println(n.getAsInt());
    } else {
      System.out.println("Is Empty");
    }
    System.out.println("---------- FindAny Example 2 -----------------");
    //Returns an OptionalInt describing some element of the stream, or an 
    //empty OptionalInt if the stream is empty.
    IntStream emptyStream = IntStream.empty();
    OptionalInt on = emptyStream.findAny();
    if (on.isPresent()) {
      System.out.println(on.getAsInt());
    } else {
      System.out.println("Is Empty");
    }
    System.out.println("---------------------------------------");
  }
}

Output:

---------- 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.

*