Close

Java 8 Streams - IntStream.findAny Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.IntStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.IntStreamIntStreamLogicBig

Method:

OptionalInt findAny()

Returns an Optional describing an element of the stream, or an empty Optional if the stream is empty.

This is a terminal-short-circuiting operation.

Examples


package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class FindAnyExample {

public static void main(String... args) {
IntStream intStream = IntStream.of(1, 2, 3, 2, 5, 4);
int i = intStream.findAny()
.orElse(-1);
System.out.println(i);
}
}

Output

1




Using findAny() method in parallel stream.

package com.logicbig.example.intstream;

import java.util.stream.IntStream;

public class FindAnyExample2 {

public static void main(String... args) {
IntStream intStream2 = IntStream.of(1, 2, 3, 2, 5, 4);
int i2 = intStream2.parallel()
.findAny()
.orElse(-1);
System.out.println(i2);
}
}

Output

2




See Also