-2
 CCMT c = new CCMT();
 c.ccd = null;
Optional<String> cType = Optional.ofNullable(ccmtRequest).map(CCMT::getCcd).map(MOEH::getDestCtry);         

System.out.println(cType.isPresent()); // false
    
if(cType.isPresent() && cType.get().equalsIgnoreCase("CCMT") || cType.get().equalsIgnoreCase("CCWC")) {
  System.out.println("wfegr");
}

ERROR: Exception NoSuchElementException

Why cType.get() statement is being executed even though first condition is false itself?

tusharRawat
  • 719
  • 10
  • 24

1 Answers1

1

This is due to operator precedence. Writing A && B || C is the same as writing (A && B) || C.

So in your case you need need to add parentheses around the || operator:

if (cType.isPresent() && (cType.get().equalsIgnoreCase("CCMT") || cType.get().equalsIgnoreCase("CCWC"))) {
    System.out.println("wfegr");
}

But using more methods of the Optional API may be more suited:

cType
    .filter(t -> t.equalsIgnoreCase("CCMT") || t.equalsIgnoreCase("CCWC"))
    .ifPresent(t -> System.out.println("wfegr"));
Lino
  • 19,604
  • 6
  • 47
  • 65