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!
Leave a Reply