Find the First Element in a Stream

Situation:
You want to retrieve the first element from a list of names.

Solution:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

Optional<String> firstName = names.stream()
    .findFirst();

System.out.println(firstName.orElse(null));

Explanation:
The findFirst method returns the first element in the stream, if present.

Result:

Alice

First come, first served! You’ve successfully retrieved the first element. Keep going strong!


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect