Eliminate NullPointerExceptions with Java Optional: Detailed Code Examples
This article demonstrates how to use Java's Optional class—through concrete examples of ofNullable, map, filter, and orElse—to safely handle potentially null objects and collections, thereby preventing NullPointerExceptions in production code.
Frequent NullPointer warnings in production prompted the author to explore Java's Optional as a way to handle nullable values more gracefully.
Case 1: Single Object
public static void main(String[] args) {
Member member = getUser(false);
// First Optional
Optional<Member> optionalMember = Optional.ofNullable(member);
// Second Optional
Optional<String> optionalNickName = optionalMember.map(Member::getNickname);
// Third Optional
optionalNickName.orElse("匿名用户");
}
private static Member getUser(boolean user) {
if (user) {
return new Member();
}
return null;
}The first call uses Optional.ofNullable, which returns Optional.empty() when the argument is null and otherwise wraps the non‑null value in an Optional<Member>. The source of ofNullable contains a ternary operator that performs this check.
The second map call transforms the contained Member into its nickname. Its implementation first verifies that the supplied function is not null, then checks whether the optional holds a value; if so, it applies the function and wraps the result in a new Optional.
The final orElse supplies a default string when the optional is empty, effectively eliminating the possibility of a NullPointerException at the call site.
Case 2: Object Containing a List
String nickname = optionalMember1
.map(Member::getPeople)
.filter(CollectionUtils::isNotEmpty)
.map(var -> var.get(0))
.orElse("用户昵称");
System.out.println(nickname);Here the author first obtains a List from the Member, uses filter to ensure the list is not empty, then extracts the first element with a second map. If any step yields an empty optional, the default string is returned.
These examples show how chaining Optional operations can replace explicit null checks, making the code more declarative and reducing the risk of runtime null dereferences.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Niuke
Focused on IT technology sharing, original and innovative content. IT Niuke, we grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
