Java 8 Stream findFirst Sample

Java 8 Stream findFirst operation is pretty straight forward in that it finds and returns the first element in the Stream. The Stream.findFirst() operation states that if the stream has no encounter order, any element may be returned.

The Stream.findFirst() 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.

findFirst() Stream of Integers

//JavaCodeDepot Sample

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


First Integer: 10

findFirst() Stream of Strings

//JavaCodeDepot Sample

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


First String: One

Add a Comment

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