-4

Am sorry, if am not clear : I am working on implementing Restful Services using Spring Boot. I am building a URI based on the request parameters. I am checking for the parameter values and based on that I need to build the URI using the parameter values. If it is NOT null I want to add it to the URI parameter. host/hello?abc="somevalue"

   MultiValueMap<String,String> params=new LinkedMultiValueMap<String,String>();
   if (null != abc) {
       params.add("abc","123");
   }

I am new to JDK 8 features.

1) How can I do this using JDK 8 optional features?

2) Is it possible both to throw an exception and log it using Optional?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Alpajna
  • 1
  • 1
  • 1
    it's not clear what you are looking for , but for null check you can use `Objects.isNull(Object obj)` – Ryuzaki L Dec 13 '18 at 03:54
  • 1
    No, with Optional it is not possible “to throw an exception and log it”, but neither does your code example. – Holger Dec 13 '18 at 07:06
  • With `Optional` it’s easy and straightforward to throw an exception in case of the value missing, if this was what you meant? I agree that it’s very unclear. And then leave to whatever code catches it whether to log it or what should be done. – Ole V.V. Dec 13 '18 at 09:58
  • I don't know what you are looking for ,if you want to check your value is null,please use `null != value` – lonecloud Dec 13 '18 at 12:46
  • 1
    see the accepted answer in [this post](https://stackoverflow.com/questions/53504573/is-using-optional-ofnullable-as-a-replacement-for-the-ternary-operator-a-good-pr) it provides some good advice as to when you should or should not use Optional and this is certainly not the case to do so. – Ousmane D. Dec 13 '18 at 21:57

1 Answers1

1

I frankly see no point in using an Optional here. The code you have is fine (we can always discuss the Yoda condition).

If you insist, you may write:

    Optional.ofNullable(abc).ifPresent(abc -> params.add("abc","123"));

Link: Yoda Conditions: To Yoda or Not to Yoda

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161