-1

I am facing a challenge where my use case is :

OrderItem orderItem = ServicesUtil.getOrderItemValue(drawStore.getOrderItem().getItem(), "Item1");

if(null==orderItem){
    orderItem = ServicesUtil.getOrderItemValue(drawStore.getOrderItem().getItem(), "Item2");
}

Here, as per the key with "Item1" if not found, my order item will be null, so I had checked for "Item2", and subsequent I can get the whole payload in case, key "Item1" is not found.

But this brings a term, where, my order item is now getting a reference to null which should never be dereferenced/accessed.

In this case, how can I filter based on the key and not really go for checking order item as null to avoid Null pointers dereferencing issue?

user-id-14900042
  • 686
  • 4
  • 17
Ranjit M
  • 138
  • 4
  • 4
  • 17
  • Does your code work currently? If it doesn't work then what's the error? (besides that's not a [example]. – user202729 Dec 06 '21 at 07:00
  • yes it works, my use case is to avoid the null check, which is causing me JSR-305 issue. – Ranjit M Dec 06 '21 at 07:02
  • Create a temporary variable, after you get the final value assign it to the variable? Or... – user202729 Dec 06 '21 at 07:04
  • There's [coalesce - How to get the first non-null value in Java? - Stack Overflow](https://stackoverflow.com/questions/2768054/how-to-get-the-first-non-null-value-in-java) or [lambda - Is there an elegant way to get the first non null value of multiple method returns in Java? - Stack Overflow](https://stackoverflow.com/questions/26118090/is-there-an-elegant-way-to-get-the-first-non-null-value-of-multiple-method-retur) . – user202729 Dec 06 '21 at 07:05
  • Still I am not clear. Please explain more. – Prasath Dec 06 '21 at 15:54

1 Answers1

0

So for resolving this, used:

Optional.ofNullable(ServicesUtil.getOrderItemValue(drawStore.getOrderItem().getItem(), "pickle")).orElseGet(()->ServicesUtil.getOrderItemValue(drawStore.getOrderItem().getItem(), "ketchup"));
Ranjit M
  • 138
  • 4
  • 4
  • 17