Streams: findAny matches findFirst only because the stream is sequential

On a sequential stream findAny happens to return the same element as findFirst because there is only one thread to satisfy it; the two are only guaranteed equal without an explicit parallel() call, since findAny may return whichever matching element a parallel stream finds fastest.

Code
List<Integer> nums = List.of(1, 2, 3, 4, 5);
Optional<Integer> first = nums.stream().filter(n -> n > 2).findFirst();
Optional<Integer> any = nums.stream().filter(n -> n > 2).findAny();
System.out.println("findFirst (sequential): " + first.get());
System.out.println("findAny (sequential): " + any.get());
Output
findFirst (sequential): 3
findAny (sequential): 3
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms