将空检查转换为可选

时间:2019-03-17 23:25:33

标签: java java-stream optional

我不明白如何使用Optional通过功能性方式更改这些空检查:

private boolean findProduct(String prodName) {
    for(OrderItem item : orderItems) {
        if(item != null) {
            Product p=item.getProduct();
            if(p != null) {
                String name = p.getProductName();
                if(name != null) {
                    if(name.equals(prodName)) return true;
                }
            }
        }
    }
    return false;       
}

3 个答案:

答案 0 :(得分:4)

使用Optional.ofNullableOptional.map

for(OrderItem item : orderItems) {
    Optional<String> prod = Optional.ofNullable(item)
            .map(OrderItem::getProduct)
            .map(Product::getProductName)
            .filter(s -> s.equals(prodName));

    if (prod.isPresent()) {
        return true;
    }
}
return false;

有关Optional.map的信息,请参见javadoc:

  

如果存在值,则将提供的映射函数应用于该值,如果结果为非null,则返回描述结果的Optional。否则,返回一个空的Optional。

答案 1 :(得分:2)

您还可以使用Stream API执行所需的操作

public void myApi1(String companyNumber){
    String url = "myURL";
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,null, future, future);
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(request);
    try{
        JSONObject response = future.get();
        JSONArray array = response.getJSONArray(("items"));
        for (int i = 0; i < array.length();i++) {
            JSONObject o = array.getJSONObject(i);
            String appointment = o.getString("links");
            String parsedAppointment = parseApp(appointment);
            Officer officer = new Officer(o.getString("name"), o.getString("officer_role"), parsedAppointment);
            Officer.officerList.add(officer);
            searchOfficerAppointments(Officer.officerList.get(i).getAppointment());
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

只需流式传输订购商品列表,映射到产品并检查是否存在具有给定名称的产品。

答案 2 :(得分:0)

排序类似于上述答案,您既可以使用流,也可以使用可选流(以及它是单线的)。

private boolean findProduct(String prodName) {
        return orderItems.stream()
                .map(Optional::ofNullable)
                .anyMatch(o -> o
                        .map(OrderItem::getProduct)
                        .map(Product::getProductName)
                        .map(s -> s.equals(prodName))
                        .isPresent());
}