🌐
OpenRewrite
docs.openrewrite.org › recipe catalog › java › modernize › java.util apis › use `getfirst()` instead of `stream().findfirst().orelsethrow()`
Use getFirst() instead of stream().findFirst().orElseThrow() | OpenRewrite Docs
import java.util.*; class Foo { void bar(SequencedCollection<String> collection) { String first = collection.stream().findFirst().orElseThrow(); } } import java.util.*; class Foo { void bar(SequencedCollection<String> collection) { String first ...
Published   3 weeks ago
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-findfirst-java-examples
Stream findFirst() in Java with examples - GeeksforGeeks
December 26, 2025 - Since the stream is not empty, the first element "Java" is printed. ... Parameters: This method does not take any parameters. Return Value: Returns an Optional<T> containing the first element of the stream and returns an empty Optional if the stream is empty. Example 1: This code demonstrates using Stream.findFirst() to retrieve the first element of a stream, returning an Optional to safely handle empty streams.
🌐
ConcretePage
concretepage.com › java › java-8 › java-stream-findfirst
Java Stream findFirst()
package com.concretepage; import java.util.Arrays; import java.util.List; public class FindFirstDemo1 { public static void main(String[] args) { List<String> list = Arrays.asList("Vijay", "Suresh", "Vinod"); String output = list.stream() .filter(e -> e.startsWith("V")) // Vijay, Vinod .findFirst() //Vijay .orElse("NA"); System.out.println(output); List<Integer> numList = Arrays.asList(31, 32, 33, 34); numList.stream() .filter(n -> n % 2 == 0) // 32, 34 .findFirst() //32 .ifPresent(e -> System.out.println(e)); } } Output · Vijay 32 Example-2: Find the example of findFirst method using IntStream, LongStream and DoubleStream. FindFirstDemo2.java ·
🌐
Blogger
javarevisited.blogspot.com › 2016 › 03 › how-to-find-first-element-of-stream-in.html
How to find the first element in Stream in Java 8? findFirst() Example
October 5, 2024 - String item = gadgets.stream() .peek(s -> System.out.println("processing: " + s)) .filter(s -> s.length() >8) .findFirst() .orElse(""); Output: processing: SmartPhone result: SmartPhone You can see that filter() has processed just one element ...
🌐
ZetCode
zetcode.com › java › stream-findfirst-findany
Java Stream findFirst/findAny - finding first or any element in Java streams
Main.java · void main() { var words = List.of("war", "cup", "cloud", "alert", "be", "ocean", "book"); var empty = List.of(); var first = words.stream().findFirst().orElse("not found"); System.out.println(first); var first2 = empty.stream().findFirst().orElse("not found"); System.out.print...
🌐
Java2s
java2s.com › Tutorials › Java › Stream_How_to › Stream › Find_first_or_return_somthing_else.htm
Java Stream How to - Find first or return somthing else
//from www. j a v a 2 s .c o m import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("HTML", "CSS", "CSS3", "Java", "SQL", "Javascript", "MySQL"); String name5 = names.stream() .map(s -> s.toUpperCase()) .filter(s -> s.length() < 5) .sorted((a, b) -> b.length() - a.length()) .findFirst() .orElse("a"); System.out.println(name5); String name2 = names.stream() .map(s -> s.toUpperCase()) .filter(s -> s.length() < 2) .sorted((a, b) -> b.length() - a.length()) .findFirst() .orElse("Somthing else"); System.out.println(name2); } } Back to Stream ↑
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream findfirst() example
Java Stream findFirst() Example
May 27, 2024 - If Stream has defined encounter order, the findFirst() returns first element in encounter order.
🌐
Jsparrow
jsparrow.github.io › rules › enhanced-for-loop-to-stream-find-first.html
Replace For-Loop with Stream::findFirst | jSparrow Documentation
Java 8, Lambda, Loop, Marker · ... if(value.length() > 4) { key = value; break; } } Post · List<String> values = generateList(input); String key = values.stream() .filter(value -> value.length() > 4) .findFirst() .orElse(""); Pre ·...
🌐
Tabnine
tabnine.com › home page › code › java › java.util.stream.stream
java.util.stream.Stream.findFirst java code examples | Tabnine
private static <T> HttpMessageWriter<T> findWriter( BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) { return context.messageWriters().stream() .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType)) .findFirst() .map(BodyInserters::<T>cast) .orElseThrow(() -> new IllegalStateException( "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\"")); }
Find elsewhere
Top answer
1 of 6
96

The reason for this is the use of Optional<T> in the return. Optional is not allowed to contain null. Essentially, it offers no way of distinguishing situations "it's not there" and "it's there, but it is set to null".

That's why the documentation explicitly prohibits the situation when null is selected in findFirst():

Throws:

NullPointerException - if the element selected is null

2 of 6
81

As already discussed, the API designers do not assume that the developer wants to treat null values and absent values the same way.

If you still want to do that, you may do it explicitly by applying the sequence

.map(Optional::ofNullable).findFirst().flatMap(Function.identity())

to the stream. The result will be an empty optional in both cases, if there is no first element or if the first element is null. So in your case, you may use

String firstString = strings.stream()
    .map(Optional::ofNullable).findFirst().flatMap(Function.identity())
    .orElse(null);

to get a null value if the first element is either absent or null.

If you want to distinguish between these cases, you may simply omit the flatMap step:

Optional<String> firstString = strings.stream()
    .map(Optional::ofNullable).findFirst().orElse(null);
System.out.println(firstString==null? "no such element":
                   firstString.orElse("first element is null"));

This is not much different to your updated question. You just have to replace "no such element" with "StringWhenListIsEmpty" and "first element is null" with null. But if you don’t like conditionals, you can achieve it also like:

String firstString = strings.stream()
    .map(Optional::ofNullable).findFirst()
    .orElseGet(()->Optional.of("StringWhenListIsEmpty"))
    .orElse(null);

Now, firstString will be null if an element exists but is null and it will be "StringWhenListIsEmpty" when no element exists.

🌐
Baeldung
baeldung.com › home › java › java streams › java stream findfirst() vs. findany()
Java Stream findFirst() vs. findAny() | Baeldung
January 9, 2024 - The findFirst() method finds the first element in a Stream. So, we use this method when we specifically want the first element from a sequence. When there is no encounter order, it returns any element from the Stream. According to the java.util.streams package documentation, “Streams may or may not have a defined encounter order.
🌐
Java67
java67.com › 2018 › 03 › java-8-stream-find-first-and-filter-example.html
Java 8 Stream filter() + findFirst Example Tutorial | Java67
Well, that's right but that's not what you should do in Java 8. That's good for Java 7 or earlier version but Java 8 offers you many better alternatives and one of them is Stream. You can use the Stream class along with filter() and findFirst() methods to find out an element based upon a Predicate, a functional interface for defining a condition which returns a boolean.
Top answer
1 of 5
33

Well, as for me, the best way is to use functional programing and continue to work with optional. So, for example if you need to pass this string to some service, you can do:

String fisrstString = myList.stream().findFirst().get();
service.doSomething(fisrstString);

But this looks not so good. Instead you can use the pros of functional programing, and do:

myList.stream().findFirst().ifPresent(service::doSomething);
2 of 5
14

You should make use of the Optional returned by findFirst() instead of trying to get its value (if it's actually present).

myList.stream()
    .findFirst()
    .ifPresent(/* consume the string here, if present */);

The Optional.ifPresent method receives a Consumer that will be used only if the Optional contains a non-null value.

The problem is that we Java developers are so used to the imperative paradigm... In particular, we are used to getting an object and pushing it i.e. to a method:

String myString = "hello"; // getting an object here

System.out.println(myString); // pushing the object to System.out here
                              // (via the println method)

With the Optional returned by Stream.findFirst() you were doing the same as above:

String myString = myList.stream()
    .findFirst()
    .get(); // getting a string here

System.out.println(myString); // pushing the string here

On the other hand, the functional paradigm (including Optional) usually works the other way:

myList.stream()
    .findFirst()
    .ifPresent(myString -> System.out.println(myString));

Here, you don't get the string and then push it to some method. Instead, you provide an argument to Optional's ifPresent operation and let the implementation of Optional push the value to your argument. In other words, you pull the value wrapped by the Optional by means of ifPresent's argument. ifPresent will then use this Consumer argument, only if the value is present.

This pull pattern is seen a lot in functional programming and is very useful, once you get used to it. It just requires us developers to start thinking (and programming) in a different way.

🌐
javaspring
javaspring.net › blog › java-stream-find-first-match
Mastering Java Stream: Find First Match — javaspring.net
import java.util.Arrays; import ... is: " + firstNumber); } } In this example, if the stream is empty, the orElse() method will return - 1 instead of throwing an exception....
🌐
Tabnine
tabnine.com › home page › code › java › java.util.optional
java.util.Optional.orElse java code examples | Tabnine
private static MediaType initDefaultMediaType(List mediaTypes) { return mediaTypes.stream().filter(MediaType::isConcrete).findFirst().orElse(null);
🌐
Scaler
scaler.com › home › topics › java stream findfirst()
Java Stream findFirst() - Scaler Topics
January 3, 2023 - In the above code, we are on purpose declaring a empty list so when our findFirst() method goes and searches for the first element it returns a NoSuchElementException . This method returns the first element from the Stream when there is an encounter ...
🌐
Java67
java67.com › 2018 › 06 › java-8-optional-example-ispresent-orElse-get.html
Java 8 Optional isPresent(), OrElse() and get() Examples | Java67
*/ public static String getBook(String letter) { Optional<String> book = listOfBooks.stream() .filter(b -> b.startsWith(letter)) .findFirst(); return book.orElse("Book Not Found"); } You can see that the OrElse() method is much nicer than the ...
🌐
TutorialsPoint
tutorialspoint.com › find-the-first-element-of-a-stream-in-java
Find the first element of a Stream in Java
July 31, 2023 - First, transform your list into ... approaches will reveal matched elements. Implement "orElse" methods for Optional objects to return null results if no matches are found....
🌐
Stack Abuse
stackabuse.com › java-8-streams-guide-to-findfirst-and-findany
Java 8 Streams: Definitive Guide to findFirst() and findAny()
November 28, 2021 - List<String> people = List.of("John", "Janette", "Maria", "Chris"); Optional<String> person = people.stream() .filter(x -> x.length() > 4) .findFirst(); Optional<String> person2 = people.stream() .filter(x -> x.length() > 4) .parallel() .findAny(); person.ifPresent(System.out::println); ...