两个 Optional 的优雅解决方案,如果一个存在,另一个不能为空

Elegant solution for two Optionals, if one is present the other must not be empty

我正在寻找此代码的更优雅的解决方案:

var first = Optional.ofNullable(a);
var second = Optional.ofNullable(b);
if ((unit.isPresent() && value.isEmpty()) || (value.isPresent() && 
     unit.isEmpty())) {
  throw new ExpWhatever();
}

条件是:

感谢任何想法或帮助。

听起来 isPresent() 恰好其中一个为真是一个错误 - 所以 XOR 工作得很好:

if (unit.isPresent() ^ value.isPresent()) {
    // Throw an exception
}

如果您希望两个选项都存在或为空(即它们具有相同的 "emptiness" 状态),您可以使用此:

if (unit.isPresent() != value.isPresent()) {
  //throw an exception
}