Close

Java 8 Streams - Stream.findAny Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

Optional<T> 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.stream;

import java.util.Optional;
import java.util.stream.Stream;

public class FindAnyExample {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
Optional<String> optionalString = s.findAny();
if(optionalString.isPresent()){
System.out.println(optionalString.get());
}
}
}

Output

one




package com.logicbig.example.stream;

import java.util.Optional;
import java.util.stream.Stream;

public class FindAnyExample2 {

public static void main(String... args) {
Stream<String> s = Stream.of("one", "two", "three", "four");
Optional<String> opt = s.parallel()
.findAny();
if (opt.isPresent()) {
System.out.println(opt.get());
}
}
}

Output

three




findAny() is a terminal-short-circuiting operation of Stream interface. This method returns any first element satisfying the intermediate operations. This is a short-circuit operation because it just needs 'any' first element to be returned and terminate the rest of the iteration.

package com.logicbig.example;

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

public class FindAnyExample {

public static void main (String[] args) {
IntStream stream = IntStream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.parallel();
stream = stream.filter(i -> i % 2 == 0);

OptionalInt opt = stream.findAny();
if (opt.isPresent()) {
System.out.println(opt.getAsInt());
}
}
}

Output

6
Original Post




See Also