🌐
GitHub
github.com › eclipse-jkube › jkube › issues › 2970
GoTimeUtilTest : Remove call to `Optional.get()` without `isPresent()` check · Issue #2970 · eclipse-jkube/jkube
April 24, 2024 - Component JKube Kit Task description Description In GoTimeUtilTest, we're directly calling Optional.get() without checking whether there is any element present in the Optional, this might cause NoS...
Author   eclipse-jkube
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 360004508920--Optional-get-is-called-without-isPresent-check-losing-information-based-on-unrelated-asserts
'Optional.get() is called without isPresent()' check losing information based on unrelated asserts – IDEs Support (IntelliJ Platform) | JetBrains
August 14, 2019 - @VisibleForTesting static Stream<FilterDifference> compareFilters( String hostname, String filtername, List<LineAction> currentActions, List<BDD> currentLineBdds, List<LineAction> referenceActions, List<BDD> referenceLineBdds) { checkArgument(!currentLineBdds.isEmpty()); checkArgument(!referenceLineBdds.isEmpty()); checkArgument(currentActions.size() == currentLineBdds.size() - 1); checkArgument(referenceActions.size() == referenceLineBdds.size() - 1); assert currentLineBdds.stream().reduce(BDD::or).get().isOne(); assert referenceLineBdds.stream().reduce(BDD::or).get().isOne(); // warning on .get()
Top answer
1 of 3
14

First of all, consider that the check is complex and probably relatively time consuming to do. It requires some static analysis, and there might be quite a bit of code between the two calls.

Second, the idiomatic usage of the two constructs are very different. I program full time in Scala, which uses Options much more frequently than Java does. I can't recall a single instance where I needed to use a .get() on an Option. You should almost always be returning the Optional from your function, or be using orElse() instead. These are much superior ways to handle missing values than throwing exceptions.

Because .get() should rarely be called in normal usage, it makes sense for an IDE to start a complex check when it sees a .get() to see if it was used properly. In contrast, iterator.next() is the proper and ubiquitous usage of an iterator.

In other words, it's not a matter of one being bad and the other not, it's a matter of one being a common case that's fundamental to its operation and is highly likely to throw an exception during developer testing, and the other being a rarely used case that may not be exercised enough to throw an exception during developer testing. Those are the sorts of cases you want IDEs to warn you about.

2 of 3
15

The Optional class is intended to be used when it is not known whether or not the item it contains is present. The warning exists to notify programmers that there is an additional possible code path that they may be able to handle gracefully. The idea is to avoid exceptions being thrown at all. The use case you present is not what it is designed for, and therefore the warning is irrelevant to you - if you actually want an exception to be thrown, go ahead and disable it (although only for this line, not globally - you should be making the decision as to whether or not to handle the not present case on an instance by instance basis, and the warning will remind you to do this.

Arguably, a similar warning should be generated for iterators. However, it has simply never been done, and adding one now would probably cause too many warnings in existing projects to be a good idea.

Also note that throwing your own exception can be more useful than just a default exception, as including a description of what element was expected to exist but didn't can be very helpful in debugging at a later point.

Top answer
1 of 1
1

You've left off a bit of information. Right now it appears your code returns Optional or null. That is the point of Optional though, it might not have anything.

if(t instanceof TileEntityMachineFrame){
    //...
} else{
    return Optional.empty();
}
    

That way you return an empty optional and not null. The next issue is your .get is giving you a warning. Since it is on an Optional, you have to consider that the Optional will be empty. The simplest replacement would be to replace get with Optional.orElse. So what happens to your constructor then?

You could replace the .get call with map.

return ( (TileEntityMachineFrame) t ).itItemHandler.map( 
    handler-> new SlotMotor( handler.motorInputWrapper, i, d.x, d.y )
);

From the javadocs for Map, "If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional. "

Breaking it down more

I think you've tried to bunch up too much, you should spread it out a bit to better understand what youre doing.

Optional<ItemHandler> opt = ( (TileEntityMachineFrame) t ).itItemHandler;
ItemHandler handler = opt.get();
SlotMotor motor = new SlotMotor( handler.motorInputWrapper, i, d.x, d.y);
Optional<SlotMotor> optionalMotor = Optional.of(motor);

In that code You're getting a warning because there is a call to get without using isPresent one way to change that is to use map.

Optional<SlotMotor> optionalMotor = opt.map( 
     handler -> new SlotMotor( handler.motorInputWrapper, i, d.x, d.y )      
);

There isn't a missing call to get because we're working inside of the lambda passed to map. Plus this automatically gets you the optional you return.

🌐
DZone
dzone.com › coding › java › java 8 optional—replace your get() calls
Java 8 Optional—Replace Your Get() Calls
July 5, 2016 - Calling get() without checking that value is actually present it’s a bug. So we should always write something like that in order to use get().\ Optional<String> myString = Optional.ofNullable(getNullableString()); if(myString.isPresent()){ doSomething(myString.get()); }
Find elsewhere
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-249482 › Inspection-Optional.get-is-called-without-isPresent-check-false-positive
Inspection `Optional.get() is called without isPresent ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - We can clean the password using a map transformation and check its correctness using a filter: @Test public void givenOptional_whenMapWorksWithFilter_thenCorrect() { String password = " password "; Optional<String> passOpt = Optional.of(password); boolean correctPassword = passOpt.filter( pass -> pass.equals("password")).isPresent(); assertFalse(correctPassword); correctPassword = passOpt .map(String::trim) .filter(pass -> pass.equals("password")) .isPresent(); assertTrue(correctPassword); }
🌐
Codemia
codemia.io › home › knowledge hub › optional.get without ispresent check
Optional.get without isPresent check | Codemia
July 31, 2025 - Optional<String> optionalString = Optional.of("Hello"); optionalString.ifPresent(val -> System.out.println("Value is: " + val)); Omitting the isPresent() check can be suitable where you have full control or certainty about the non-null existence of value at runtime, such as:
🌐
Jsparrow
jsparrow.github.io › rules › optional-if-present-or-else.html
Use Optional::ifPresentOrElse | jSparrow Documentation
int i = 0; i++; if(optional.isPresent()) { String value = optional.get(); consume(value); i++; } else { consume("No value"); } You can auto-refactor this with jSparrow. Drop this button to your Eclipse IDE workspace to install jSparrow for free: Need help? Check out our installation guide.
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-220751
Optional.get() is called without isPresent() check inconsistent
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Learn IT University
learn-it-university.com › home › the dangers of using optional.get() without ispresent() check: best practices explained
The Dangers of Using Optional.get() Without isPresent() Check: Best Practices Explained - Learn IT University
July 21, 2024 - Handling optional values in Java can sometimes be tricky, especially when you consider the potential consequences of using Optional.get() without a preceding isPresent() check. In this article, we’ll explore why it’s important to avoid directly using get(), and we’ll discuss a more robust approach by leveraging methods like orElse(null).
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-224757 › Optional.get-without-isPresent-inspection-should-not-be-displayed
Optional.get without isPresent inspection should not be ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-152373
Optional.get without Optional.isPresent warning when check is ...
August 9, 2022 - {{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - This method supports post-processing on optional values, without the need to explicitly check for a return status.
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-153922 › Optionalget-without-isPresent-check-when-used-in-ifPresents-consumer
"Optional.get() without isPresent" check when used in ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
JetBrains
youtrack.jetbrains.com › issue › IDEA-188966 › Add-dedicated-suppression-for-Optional.get-without-isPresent-check
Add dedicated suppression for "Optional.get() without ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong