Dadonis
Dadonis

Reputation: 87

JAVA8 two for each loops to stream

Hello I have two loops iterating through lists and setting name property using switch, but i want to refactor and use streams instead but not sure how to do it:

here's the code snippet

for (ClaimDTO claimDTO: claimDTOs) {
    for (CategoryDTO categoryDTO : claimDTO.getCategories()) {
        switch (categoryDTO.getCategoryType()) {
            case "ALLOWANCE": {
                categoryDTO.setName("Flight");
                break;
            }
            case "MILEAGE": {
                categoryDTO.setyName("Car");
                break;
            }
            default:
                categoryDTO.setName("Expenses");

         }
    }
}

Should i create function for resolving name and just use it in stream or it's not even worth and will not save LOC.

Upvotes: 0

Views: 315

Answers (1)

eee
eee

Reputation: 3458

You can use flatMap to get all category dtos in a single stream:

claimDTOs.stream()
    .flatMap(claim -> claim.getCategories().stream())
    .forEachOrdered(this::setName);

forEachOrdered then takes a Consumer which is executed for every element and can be referenced as a method reference (double colons).

private void setName(CategoryDTO categoryDTO) {
    switch (categoryDTO.getCategoryType()) {
        case "ALLOWANCE": {
            categoryDTO.setName("Flight");
            break;
        }
        case "MILEAGE": {
            categoryDTO.setName("Car");
            break;
        }
        default:
            categoryDTO.setName("Expenses");

    }
}

Upvotes: 1

Related Questions