简体   繁体   中英

Refactor for loop using java 8 streams

I want to replace below for loop with java 8 streams. Any help will be much appreciated. Thank you.

OwnerEntity oEntity = new OwnerEntity();

// sorted set based on last change date descending order
Set<StatusModel> stsModels = getStatsModelSetSortedByChangeDateDesc();
for (int i = 0; i < stsModels.size(); i++) {
    StatusModel sts = stsModels.get(i);
    if (i == 0 && !sts.getStatus().equals("0")) {
        // only for first lelement in the list status is '0' then break
        //do not process the list further
        break;
    }
    // otherwise add the elements of the list to OwnerEntity Object

    if (sts.egtStatus() != null && (acctNumber.equalsIgnoreCase(sts.getAccountNumber()))) {
        oEntity.addStatusModel(sts);
    }
}

I would suggest something like this:

OwnerEntity oEntity = new OwnerEntity();

// sorted set based on last change date descending order
Set<StatusModel> stsModels = getStatsModelSetSortedByChangeDateDesc();

if (stsModels.size() > 0 && !stsModels.get(0).equals("0")) {
    stsModels.stream()
             .filter(sts -> sts.egtStatus() != null && (acctNumber.equalsIgnoreCase(sts.getAccountNumber())))
             .forEach(sts -> oEntity.addStatusModel(sts));
}

I think you should have 2 steps, first check if first have status not equals to 0

If exists than filter the other conditions

    //retrive first element if status not 0
    List<StatusModel> result = new ArrayList<>();
    Optional<StatusModel> firstElement =
            stsModels.stream()
                    .findFirst()
                    .filter(f -> !f.getStatus().equals("0"));

    if(firstElement.isPresent()) {
    //other stream with logic
        result= stsModels.stream()
                .filter(f -> f.getStatus() != null
                        && accountnumber.equalsIgnoreCase(f.getGetAccountNumber()))
                .collect(Collectors.toList());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM