如何在Java中使用可选类防止NosuchelementException

发布于 2025-02-01 21:11:12 字数 948 浏览 5 评论 0原文

在使用流API的用户定义的类类型列表中过滤时,在某些情况下,对于给定条件,在 list 中找不到元素。

如何在这种情况下预防异常并根据业务逻辑使用可选类处理?

流API方法看起来像:

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {
    
    Optional<Policy> policy = Optional.of(policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst().get());
    
    return policy;
}

调用代码看起来像:

Optional<Policy> updatedPolicyOptional = getPolicy(updatedPolies,policykey); // <- exception is being generated here

if (updatedPolicyOptional.isPresent()) {
    // business logic
}
else {
    // business logic
}

输出:

Verify audit report for update made in TC_08
java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)

While filtering through a list of user defined class type using Stream API has been encountered some cases where no element has been found in the list for given condition.

How to prevent exception in such case and handle according to business logic using optional class?

Stream API method looks like :

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {
    
    Optional<Policy> policy = Optional.of(policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst().get());
    
    return policy;
}

The calling code looks like that:

Optional<Policy> updatedPolicyOptional = getPolicy(updatedPolies,policykey); // <- exception is being generated here

if (updatedPolicyOptional.isPresent()) {
    // business logic
}
else {
    // business logic
}

Output :

Verify audit report for update made in TC_08
java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋情葬爱 2025-02-08 21:11:12

为了再次将其包裹起来,无需从可选对象中提取结果。

这是毫无意义的,如果不存在结果,将触发nosuchelementException。要解决问题,请删除get()的呼叫,在这种情况下,它不安全和多余:

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {
    
    return policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst();
}

为了流利地实现您的条件逻辑,您可以使用 optional.ifpresentorelse() 期望如果存在结果,将执行contumer,并且runnable该该如果可选为空,将发射。请注意,Java 9可以访问此方法。

getPolicy(updatedPolies,policykey)
    .ifPresentOrElse(policy -> doSomething(policy), 
                     () -> doSomethingElse());

使用Java 8,您可以使用 optional.ifpresent() EM> IFPRESENTORELSE在JDK 8 中不可评估,它期望消​​费者,并且它将覆盖条件逻辑的一部分。要涵盖else部分(*空置可选的情况),您将需要一个条件。

Optional<Policy> policy = getPolicy(updatedPolies,policykey);
    
policy.ifPresent(policy -> doSomething(policy));
        
if (!policy.isPresent()) doSomethingElse();

There's no need to extract the result from the optional object just in order to wrap it with an optional again.

It's pointless and will trigger NoSuchElementException if result is not present. To solve the problem, remove the call of get() which both unsafe and redundant in this case:

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {
    
    return policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst();
}

In order implement your conditional logic fluently you can make use of Optional.ifPresentOrElse() which expects a Consumer that would be executed if result is present and a Runnable that will be fired in case if optional is empty. Note, this method is accessible with Java 9.

getPolicy(updatedPolies,policykey)
    .ifPresentOrElse(policy -> doSomething(policy), 
                     () -> doSomethingElse());

With Java 8 you can use only Optional.ifPresent() (ifPresentOrElse is not evaluable in JDK 8) that expects consumer, and it'll cover the if part of conditional logic. To cover the else part (*the case of empty optional), you will need a condition.

Optional<Policy> policy = getPolicy(updatedPolies,policykey);
    
policy.ifPresent(policy -> doSomething(policy));
        
if (!policy.isPresent()) doSomethingElse();
伤感在游骋 2025-02-08 21:11:12

findfirst()已经返回可选,尝试get> get()它在空为空时会导致错误。因此,您的功能应该是:

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {    
    return = policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst();        
}

并且取决于您的Java版本(您的业务逻辑),您可以使用以下内容:

java8。

if (updatedPolicyOptional.isPresent()) {
    // business logic
}
else {
    // business logic
}

T value = updatedPolicyOptional(mapToTFunctor).orElse(someTValue);

java9。

updatedPolicyOptional.ifPresentOrElse(someConsumer,someNoParamFunctor);

findFirst() already returns an Optional, trying to get() it leads to an error when it is empty. So your function should be:

public static Optional<Policy> getPolicy(ReturnTermPolicy policyType, 
                                         String policyKey) {    
    return = policyType.getPolicies().stream()
        .filter(temp -> temp.getPolicyKey().equals(policyKey))
        .findFirst();        
}

And depending on your Java version (and your business logic) you can use things like:

Java 8.

if (updatedPolicyOptional.isPresent()) {
    // business logic
}
else {
    // business logic
}

or

T value = updatedPolicyOptional(mapToTFunctor).orElse(someTValue);

Java 9.

updatedPolicyOptional.ifPresentOrElse(someConsumer,someNoParamFunctor);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文