Java 8 Stream findAny Sample

Java 8 Stream findAny operation, which is very intuitive, will find any element from a given Stream. To be used when you are looking for an element without concern for the encounter order. The behavior of findAny() is nondeterministic, which means it is free to select any element in the stream.

The Stream.findAny() operation will return an Optional instance. If your not familiar with Optional Class, it is a container object which may or may not contain a non-null value. If the element selected from the Stream is null, a NullPointerException is thrown.

findAny() Stream of Integers

//JavaCodeDepot Sample

public static void findAnyInt() {
		
	List<Integer> jcdIntList = Arrays.asList(10, 20, 30, 40, 50);
		
	Optional<Integer> jcdResult = jcdIntList.stream().findAny();
		
	System.out.println("Any Integer: "+jcdResult.get());
}

Output:

Any Integer: 10


findAny() Stream of Strings

//JavaCodeDepot Sample

public static void findAnyString() {
		
	List<String> jcdStringList = Arrays.asList("One", "Two", "Three", "Four", "Five");
		
	Optional<String> jcdResult = jcdStringList.stream().findAny();
		
	System.out.println("Any String: "+jcdResult.get());
}

Output:

Any String: One


It is important to note that if your doing a non-parallel operation with Stream.findAny(), the operation will most likely return the first element in the Stream. Because of this behavior, the findFirst() and findAny() Stream operation is very similar.

Add a Comment

Your email address will not be published. Required fields are marked *