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;








2















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.










share|improve this question





















  • 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















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.










share|improve this question





















  • 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








2








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.










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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












  • 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












3 Answers
3






active

oldest

votes


















5
















Seems like a use case for ifPresentOrElse as in Java-9 :



obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );





share|improve this answer

























  • Good solution. The return; 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 of return as well!

    – Naman
    Mar 28 at 8:53



















2
















If you want to do nothing when the Optional is empty, you can use ifPresent:



public void someMethod() 
someService.getObj().ifPresent (v ->
....
);






share|improve this answer

























  • 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


















0
















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.






share|improve this answer



























  • 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













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
);



);














draft saved

draft discarded
















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









5
















Seems like a use case for ifPresentOrElse as in Java-9 :



obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );





share|improve this answer

























  • Good solution. The return; 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 of return as well!

    – Naman
    Mar 28 at 8:53
















5
















Seems like a use case for ifPresentOrElse as in Java-9 :



obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );





share|improve this answer

























  • Good solution. The return; 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 of return as well!

    – Naman
    Mar 28 at 8:53














5














5










5









Seems like a use case for ifPresentOrElse as in Java-9 :



obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );





share|improve this answer













Seems like a use case for ifPresentOrElse as in Java-9 :



obj.ifPresentOrElse(a -> ..., () -> logger.info(xxxx);return; );






share|improve this answer












share|improve this answer



share|improve this answer










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. The return; 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 of return as 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






  • 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

















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














2
















If you want to do nothing when the Optional is empty, you can use ifPresent:



public void someMethod() 
someService.getObj().ifPresent (v ->
....
);






share|improve this answer

























  • 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















2
















If you want to do nothing when the Optional is empty, you can use ifPresent:



public void someMethod() 
someService.getObj().ifPresent (v ->
....
);






share|improve this answer

























  • 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













2














2










2









If you want to do nothing when the Optional is empty, you can use ifPresent:



public void someMethod() 
someService.getObj().ifPresent (v ->
....
);






share|improve this answer













If you want to do nothing when the Optional is empty, you can use ifPresent:



public void someMethod() 
someService.getObj().ifPresent (v ->
....
);







share|improve this answer












share|improve this answer



share|improve this answer










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

















  • 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











0
















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.






share|improve this answer



























  • 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















0
















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.






share|improve this answer



























  • 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













0














0










0









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.






share|improve this answer















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.







share|improve this answer














share|improve this answer



share|improve this answer








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

















  • 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


















draft saved

draft discarded















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해