findFirst and findAny
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)findFirst and findAny are terminal operations that return one element of a stream, wrapped in an Optional. findFirst returns the first element in encounter order; findAny returns whichever element is quickest to get.
findFirst after filter
A common question is "give me the first one that matches": the first CSE student in the admission list, the first train with free seats, the first failed payment.
Example 1 · findFirst: the first CSE student in admission order
import java.util.List;import java.util.Optional;
record Student(String name, String branch, int rank) {}
public class FindFirstDemo { public static void main(String[] args) { // admission order List<Student> admitted = List.of( new Student("Aarav", "ECE", 1520), new Student("Priya", "CSE", 980), new Student("Rohan", "MECH", 3100), new Student("Kavya", "CSE", 450), new Student("Divya", "ECE", 2200));
// old way: loop, if, break Student firstCseLoop = null; for (Student s : admitted) { if (s.branch().equals("CSE")) { firstCseLoop = s; break; } } System.out.println("Loop: " + firstCseLoop.name());
Optional<Student> firstCse = admitted.stream() .filter(s -> s.branch().equals("CSE")) .findFirst(); System.out.println("Stream: " + firstCse.get().name()); System.out.println("Optional: " + firstCse); }}Loop: Priya Stream: Priya Optional: Optional[Student[name=Priya, branch=CSE, rank=980]]
What this code does
filterkeeps the CSE students andfindFirstreturns the first of them in list order: Priya, who was admitted before Kavya.- Kavya has the better rank, but
findFirstdoes not compare anything. "First" means first in encounter order; for the best rank you would usemin(Comparator.comparingInt(Student::rank)).
Example 2 · Trap: findFirst is not the smallest
import java.util.Comparator;import java.util.List;
public class FirstNotSmallestDemo { public static void main(String[] args) { List<Integer> hostelFees = List.of(52000, 45000, 61000, 38000, 41000);
int firstUnder50k = hostelFees.stream() .filter(f -> f < 50000) .findFirst() .orElse(0); int cheapestUnder50k = hostelFees.stream() .filter(f -> f < 50000) .min(Comparator.naturalOrder()) .orElse(0); int viaSorted = hostelFees.stream() .filter(f -> f < 50000) .sorted() .findFirst() .orElse(0);
System.out.println("First under 50k: " + firstUnder50k); System.out.println("Cheapest under 50k: " + cheapestUnder50k); System.out.println("Sorted, then first: " + viaSorted); }}First under 50k: 45000 Cheapest under 50k: 38000 Sorted, then first: 38000
What this code does
findFirstreturns 45000 because it is the first fee under 50000 in the list. It never compares fees, so the cheaper 38000 later in the list is ignored.sorted().findFirst()also gives the smallest, but it sorts every fee first, O(n log n).minreads the list once, O(n), and says what you mean.
The old way is a loop with an if, a variable to hold the answer, and a break. With a stream, you filter and then call findFirst(): students.stream().filter(s -> s.branch().equals("CSE")).findFirst(). It returns an Optional<Student>, because there may be no CSE student at all.
First means first in encounter order: the order of the list, or the order after sorted. It does not mean the smallest. For the smallest, use min with a comparator.
It stops at the first match
findFirst and findAny are short-circuiting, like the match operations. Once an element reaches the end of the pipeline, the stream stops. Every earlier lazy step stops with it.
Example 3 · Only the elements up to the first match are processed
import java.util.List;
public class FindFirstLazyDemo { public static void main(String[] args) { List<String> trains = List.of("12627:0", "12628:0", "16526:14", "12677:3", "16595:22");
String firstWithSeats = trains.stream() .peek(t -> System.out.println("checking " + t)) .filter(t -> Integer.parseInt(t.split(":")[1]) > 0) .map(t -> t.split(":")[0]) .findFirst() .orElse("none");
System.out.println("Book train " + firstWithSeats); }}checking 12627:0 checking 12628:0 checking 16526:14 Book train 16526
What this code does
- Each String is a train number and its free seats. The first two trains are full, the third has 14 seats, so
findFirststops there. The last two trains are never checked. mapruns beforefindFirst, so the result is just the train number.orElse("none")gives a safe default if every train were full.
So in orders.stream().map(this::loadDetails).filter(o -> o.isLate()).findFirst(), loadDetails runs only until the first late order is found. On a list of a lakh orders, that can be a handful of calls instead of a lakh. When the source has no order, such as a HashSet, there is no real "first". findFirst then returns some element, and you should not rely on which.
findAny and parallel streams
findAny() promises only "some matching element". On a sequential stream it usually returns the same element as findFirst, but the documentation does not promise that.
Example 4 · findAny on a parallel stream
import java.util.ArrayList;import java.util.List;
public class FindAnyDemo { public static void main(String[] args) { List<Integer> tickets = new ArrayList<>(); for (int i = 1; i <= 1000; i++) { tickets.add(i); }
int seqAny = tickets.stream().filter(t -> t % 7 == 0).findAny().get(); System.out.println("Sequential findAny: " + seqAny);
for (int run = 1; run <= 3; run++) { int first = tickets.parallelStream().filter(t -> t % 7 == 0).findFirst().get(); int any = tickets.parallelStream().filter(t -> t % 7 == 0).findAny().get(); System.out.println("Run " + run + ": findFirst " + first + ", findAny " + any); } }}Sequential findAny: 7 Run 1: findFirst 7, findAny 329 Run 2: findFirst 7, findAny 658 Run 3: findFirst 7, findAny 658
What this code does
- Ticket numbers 1 to 1000; we want one that is a multiple of 7.
findFirstalways gives 7, the first in list order, even in parallel. - Parallel
findAnyreturned 329 and then 658: whichever thread found a match first won, andfindAnytook it without waiting. Both answers are correct for "any multiple of 7"; onlyfindFirstpromises which one.
The difference shows on a parallel stream, which splits the data into chunks and checks them on several threads at once. findAny takes the first match that any thread finds, so it can return an element from the middle of the list. findFirst must return the element that is first in encounter order, so threads have to wait for the earlier chunks. That waiting makes findFirst slower in parallel. Use findFirst when the order matters (the first applicant, the earliest log line). Use findAny when any match will do ("is there a free delivery partner nearby? give me one"), especially on a parallel stream.
Handling the Optional result safely
Both methods return an Optional<T>, a box holding one value or nothing. Read it with orElse(default), ifPresent(action), or ifPresentOrElse(action, emptyAction), which runs the first lambda when there is a value and the second when there is not. get() throws NoSuchElementException on an empty box.
Example 5 · Reading the Optional result safely
import java.util.List;import java.util.Optional;
record Student(String name, String branch) {}
public class SafeFindDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", "ECE"), new Student("Priya", "CSE"), new Student("Kavya", "CSE"));
for (String branch : List.of("CSE", "MECH")) { Optional<Student> first = students.stream() .filter(s -> s.branch().equals(branch)) .findFirst();
System.out.println(branch + " present? " + first.isPresent());
first.ifPresentOrElse( s -> System.out.println(" First " + branch + " student: " + s.name()), () -> System.out.println(" No " + branch + " student yet"));
String name = students.stream() .filter(s -> s.branch().equals(branch)) .map(Student::name) .findFirst() .orElse("none"); System.out.println(" Name or default: " + name); } }}CSE present? true First CSE student: Priya Name or default: Priya MECH present? false No MECH student yet Name or default: none
What this code does
ifPresentOrElsetakes two lambdas: one for a value, one for an empty result. The code never callsget(), so it cannot throw.- Mapping to the name before
findFirstturns the result into anOptional<String>, soorElse("none")gives a ready-to-print String.
A neat pattern is to map the stream to the field you need before findFirst: students.stream().filter(...).map(Student::name).findFirst().orElse("none"). You get a String with a default in one chain. One more trap: if the element found is null, findFirst throws a NullPointerException, because an Optional cannot hold null. Filter out nulls first with filter(Objects::nonNull) when your data can contain them.
Fix the error
Fix the empty Optional
Read the real error, then pick the line that fixes it.
Round 1 of 2
No mark is below 40, so the Optional is empty.
Error
Exception in thread "main" java.util.NoSuchElementException: No value present at FirstFail.main(FirstFail.java:6)
Next step
Check your understanding
11 quick questions