Java8 lambda用于检查两个条件 [英] Java8 lambda for checking two conditions

查看:1092
本文介绍了Java8 lambda用于检查两个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段,尝试将其更改为lambda函数.

I have the following code snippet which I would try to change to the lambda function.

if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}

我以某种方式编写了如下所示的内容,但是不知道是否合并了 dogList 检查条件

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition

Optional.of(catList) 
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE

有人可以帮我吗

推荐答案

您可以在第一个Optional

Optional o = Optional.of(catList) 
                     .map(catList -> ...)
                     .orElse(Optional.of(dogList)
                                     .map(dogList -> ...));

或使用Stream的其他方法,如果您可以使对服务的调用足够通用

Or other method using Stream if you can make the call to the service generic enough

或其他使用Stream#of

它将基本上遍历两个列表,找到第一个不为null的列表(但如果需要,您可以在过滤器中添加其他条件),然后将泛型调用应用于服务.

It will basically go through both lists, find the first that is not null (but you can add other conditions to your filter if you want) and apply the generic call to service.

Optional o = Stream.of(catList, dogList)
                   .filter(Objects::nonNull /*or other condition if you want*/)
                   .findFirst()
                   .map(list -> /*generic call to service*/);

并以这种方式调用

if (!o.isPresent()) return;

这篇关于Java8 lambda用于检查两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆