Java 8 How to return from a method if Optional is not present?How do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How to avoid Java code in JSP files?How to split a string in JavaHow do I convert a String to an int in Java?
Do ibuprofen or paracetamol cause hearing loss?
Will replacing a fake visa with a different fake visa cause me problems when applying for a legal study permit?
Do all humans have an identical nucleotide sequence for certain proteins, e.g haemoglobin?
Is it appropriate for a professor to require students to sign a non-disclosure agreement before being taught?
Can I disable a battery powered device by reversing half of its batteries?
Dividing Divisive Divisors
How to split a string by the third .(dot) delimiter
Why should I always enable compiler warnings?
The Royal Mint of Alphagonia
Relevance of the Resurrection
Are there take-over requests from autopilots?
Does the wording of the Wrathful Smite spell imply that there are other living beings that aren't considered "creatures"?
Dominant 7th chords
Variable Prefixes and Suffixes
What is Japanese Language Stack Exchange called in Japanese?
What's the biggest organic molecule that could have a smell?
Why didn't Thor use the All powerful spear instead of Stormbreaker?
How could a imperial dynasty keep a loose collection of pirates, raiders, etc unified?
Have there been any countries that voted themselves out of existence?
Is the definition of integral extension, why we use monic polynomial?
Why did it become so much more expensive to start a university?
Why would "an mule" be used instead of "a mule"?
Kingdom Map and Travel Pace
Are Democrats more likely to believe Astrology is a science?
Java 8 How to return from a method if Optional is not present?
How do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How to avoid Java code in JSP files?How to split a string in JavaHow do I convert a String to an int in Java?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I don't means return a Optional value, I mean for a method:
public void someMethod()
Optional<Obj> obj = someService.getObj();
if (obj.isPresent())
....
else
log.info(xxxx);
return;
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxx
other codes
Is is possible to write it with Optional.ifPresent way? I mean, avoid to use the if isPresent thing.
Many thanks.
== updated:
it seems ifPresentOrElse in JDK9 can do this, but is there any way to do this in JAVA8?
I don't need this method return any value, but if the Optional not present, I want to log something.
java lambda optional
add a comment |
I don't means return a Optional value, I mean for a method:
public void someMethod()
Optional<Obj> obj = someService.getObj();
if (obj.isPresent())
....
else
log.info(xxxx);
return;
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxx
other codes
Is is possible to write it with Optional.ifPresent way? I mean, avoid to use the if isPresent thing.
Many thanks.
== updated:
it seems ifPresentOrElse in JDK9 can do this, but is there any way to do this in JAVA8?
I don't need this method return any value, but if the Optional not present, I want to log something.
java lambda optional
2
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47
add a comment |
I don't means return a Optional value, I mean for a method:
public void someMethod()
Optional<Obj> obj = someService.getObj();
if (obj.isPresent())
....
else
log.info(xxxx);
return;
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxx
other codes
Is is possible to write it with Optional.ifPresent way? I mean, avoid to use the if isPresent thing.
Many thanks.
== updated:
it seems ifPresentOrElse in JDK9 can do this, but is there any way to do this in JAVA8?
I don't need this method return any value, but if the Optional not present, I want to log something.
java lambda optional
I don't means return a Optional value, I mean for a method:
public void someMethod()
Optional<Obj> obj = someService.getObj();
if (obj.isPresent())
....
else
log.info(xxxx);
return;
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxx
other codes
Is is possible to write it with Optional.ifPresent way? I mean, avoid to use the if isPresent thing.
Many thanks.
== updated:
it seems ifPresentOrElse in JDK9 can do this, but is there any way to do this in JAVA8?
I don't need this method return any value, but if the Optional not present, I want to log something.
java lambda optional
java lambda optional
edited Mar 28 at 14:19
Niuhuru Lang
asked Mar 28 at 8:44
Niuhuru LangNiuhuru Lang
2251 silver badge18 bronze badges
2251 silver badge18 bronze badges
2
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47
add a comment |
2
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47
2
2
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47
add a comment |
3 Answers
3
active
oldest
votes
Seems like a use case for ifPresentOrElse as in Java-9 :
obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );
Good solution. Thereturn;inside the lambda doesn’t do what you think.
– Ole V.V.
Mar 28 at 8:51
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use ofreturnas well!
– Naman
Mar 28 at 8:53
add a comment |
If you want to do nothing when the Optional is empty, you can use ifPresent:
public void someMethod()
someService.getObj().ifPresent (v ->
....
);
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
add a comment |
Just throwing an idea out there, what about having a method on the service to check if the object is present?
I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.
On SomeService:
public boolean isObjectPresent()
return getObj().isPresent();
Then
public void someMethod()
if (someService.isObjectPresent())
....
else
log.info(xxxx);
return;
This way you don't have to deal with the Optional in your call as you don't really care about its value
NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55393299%2fjava-8-how-to-return-from-a-method-if-optional-is-not-present%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Seems like a use case for ifPresentOrElse as in Java-9 :
obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );
Good solution. Thereturn;inside the lambda doesn’t do what you think.
– Ole V.V.
Mar 28 at 8:51
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use ofreturnas well!
– Naman
Mar 28 at 8:53
add a comment |
Seems like a use case for ifPresentOrElse as in Java-9 :
obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );
Good solution. Thereturn;inside the lambda doesn’t do what you think.
– Ole V.V.
Mar 28 at 8:51
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use ofreturnas well!
– Naman
Mar 28 at 8:53
add a comment |
Seems like a use case for ifPresentOrElse as in Java-9 :
obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );
Seems like a use case for ifPresentOrElse as in Java-9 :
obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );
answered Mar 28 at 8:50
NamanNaman
51.9k14 gold badges111 silver badges216 bronze badges
51.9k14 gold badges111 silver badges216 bronze badges
Good solution. Thereturn;inside the lambda doesn’t do what you think.
– Ole V.V.
Mar 28 at 8:51
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use ofreturnas well!
– Naman
Mar 28 at 8:53
add a comment |
Good solution. Thereturn;inside the lambda doesn’t do what you think.
– Ole V.V.
Mar 28 at 8:51
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use ofreturnas well!
– Naman
Mar 28 at 8:53
Good solution. The
return; inside the lambda doesn’t do what you think.– Ole V.V.
Mar 28 at 8:51
Good solution. The
return; inside the lambda doesn’t do what you think.– Ole V.V.
Mar 28 at 8:51
1
1
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use of
return as well!– Naman
Mar 28 at 8:53
@OleV.V. It's not of much use agreed. But not sure what in the current context is the use of
return as well!– Naman
Mar 28 at 8:53
add a comment |
If you want to do nothing when the Optional is empty, you can use ifPresent:
public void someMethod()
someService.getObj().ifPresent (v ->
....
);
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
add a comment |
If you want to do nothing when the Optional is empty, you can use ifPresent:
public void someMethod()
someService.getObj().ifPresent (v ->
....
);
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
add a comment |
If you want to do nothing when the Optional is empty, you can use ifPresent:
public void someMethod()
someService.getObj().ifPresent (v ->
....
);
If you want to do nothing when the Optional is empty, you can use ifPresent:
public void someMethod()
someService.getObj().ifPresent (v ->
....
);
answered Mar 28 at 8:48
EranEran
308k40 gold badges520 silver badges597 bronze badges
308k40 gold badges520 silver badges597 bronze badges
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
add a comment |
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
However you can't return the obj, because ifPresent is void method, you can only do something with your object. To return value, use if (obj.isPresent())
– Taavi Kivimaa
Mar 28 at 8:49
1
1
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
@TaaviKivimaa based on the void method the OP posted, I assumed there's no need to return anything.
– Eran
Mar 28 at 8:49
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
OP's english got me confused there, thought he was trying to return something inside the if statement and set a bad example code with void method.
– Taavi Kivimaa
Mar 28 at 8:57
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
Thanks for your answer. Sorry I don't need to return any value, but I want to log something if not present.
– Niuhuru Lang
Mar 28 at 14:20
add a comment |
Just throwing an idea out there, what about having a method on the service to check if the object is present?
I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.
On SomeService:
public boolean isObjectPresent()
return getObj().isPresent();
Then
public void someMethod()
if (someService.isObjectPresent())
....
else
log.info(xxxx);
return;
This way you don't have to deal with the Optional in your call as you don't really care about its value
NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
add a comment |
Just throwing an idea out there, what about having a method on the service to check if the object is present?
I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.
On SomeService:
public boolean isObjectPresent()
return getObj().isPresent();
Then
public void someMethod()
if (someService.isObjectPresent())
....
else
log.info(xxxx);
return;
This way you don't have to deal with the Optional in your call as you don't really care about its value
NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
add a comment |
Just throwing an idea out there, what about having a method on the service to check if the object is present?
I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.
On SomeService:
public boolean isObjectPresent()
return getObj().isPresent();
Then
public void someMethod()
if (someService.isObjectPresent())
....
else
log.info(xxxx);
return;
This way you don't have to deal with the Optional in your call as you don't really care about its value
NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.
Just throwing an idea out there, what about having a method on the service to check if the object is present?
I think that generally you don't want to spread your Optionals all over your code, I'd prefer to keep it inside the service.
On SomeService:
public boolean isObjectPresent()
return getObj().isPresent();
Then
public void someMethod()
if (someService.isObjectPresent())
....
else
log.info(xxxx);
return;
This way you don't have to deal with the Optional in your call as you don't really care about its value
NOTE: Also, I'd add that if you have no code after the if blocks, you don't need the return statement.
edited Mar 28 at 9:01
answered Mar 28 at 8:55
BentayeBentaye
5,5323 gold badges23 silver badges33 bronze badges
5,5323 gold badges23 silver badges33 bronze badges
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
add a comment |
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
Thanks for your idea. This is just an example, I have more codes after the if. so I must return if not present. sorry I didn't mention that, I adjusted my question.
– Niuhuru Lang
Mar 28 at 14:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55393299%2fjava-8-how-to-return-from-a-method-if-optional-is-not-present%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
If you want to return if the Optional isn't present, the if/else statement looks good to me. Can't think why you'd want or need to do it another way
– Chris Neve
Mar 28 at 8:47