将for循环转换为Java 8 Stream

时间:2017-04-28 14:51:28

标签: java-8 java-stream

我需要将这些代码转换为Java 8 Stream我使用下面给出的代码尝试了它,但我仍然没有得到我想要的。

//contractList is list of Contract class
//contract.getProgramId() returns String
//contract.getEnrollmentID() returns String
//'usage = CommonUtils.getUsageType()' is other service to call wich returns String
//enroll and usage are String type
//enrollNoWithUsageTypeJson is json object '{"enroll": value, "usage": value}'
//usages is List<JSONObject> where enrollNoWithUsageTypeJson need to add

for (Contract contract : contractList) {
    if (!StringUtils.isEmpty(contract.getProgramId())) {
        enroll = contract.getEnrollmentID();
        usage = CommonUtils.getUsageType(envProperty, contract.getProgramId());
        if (!(StringUtils.isEmpty(enroll) || StringUtils.isEmpty(usage))) {
            enrollNoWithUsageTypeJson.put("enroll", enroll);
            enrollNoWithUsageTypeJson.put("usage", usage);
            usages.add(enrollNoWithUsageTypeJson);
        }
    }
}

到现在为止,我得到了:

contractList.stream()
    .filter(contract -> !StringUtils.isEmpty(contract) &&
            !StringUtils.isEmpty(contract.getProgramId()))

    .collect(Collectors.to);

提前Thakyou:)

1 个答案:

答案 0 :(得分:4)

以下是基于流的代码版本的外观(根据需要添加静态导入):

List<JSONObject> usages = contractList.stream()
    .filter(c -> isNotEmpty(c.getProgramId()))
    .map(c -> new SimpleEntry<>(c.getEnrollmentID(), getUsageType(envProperty, c.getProgramId())))
    .filter(e -> isNotEmpty(e.getKey()) && isNotEmpty(e.getValue())))
    .map(e -> {
        enrollNoWithUsageTypeJson.put("enroll", e.getKey());
        enrollNoWithUsageTypeJson.put("usage", e.getValue());
        return enrollNoWithUsageTypeJson; })
    .collect(toList());

我冒昧地使用来自Apache Commons的isNotEmpty,因为这个选项!isEmpty看起来很糟糕。我(ab)使用AbstractMap.SimpleEntry来保存一对值。如果您感觉getKeygetValue使代码的可读性降低,您可以引入一个类来保存这两个变量。 E.g:

class EnrollUsage {
    String enroll, usage;
}

您可能还希望定义一种方法:

JSONObject withEnrollAndUsage(JSONObject json, String enroll, String usage) {
    json.put("enroll", enroll);
    json.put("usage", usage);
    return json;
}

并在上面使用:

.map(e -> withEnrollAndUsage(enrollNoWithUsageTypeJson, e.getKey(), e.getValue()))

请记住,您从未真正“需要”将代码转换为使用流。有些情况下使用流虽然在理智上令人满意,但实际上会使代码复杂化。在这种情况下,你要做出最好的判断。