Home > Enterprise >  How to convert this For Loop into a Stream?
How to convert this For Loop into a Stream?

Time:12-22

I am trying to convert a for loop into a stream. The For loops below works however I am expected to use stream in my coding practises but am new to the concept. I have tried looking at examples online however the issue I run into is how to use the forEach to iterate through the list and to apply a function to each.

private List<Breakdown> createBreakdownList(final Encounter encounter, final Amount allowedAmt, final Amount discountAmt) {

int size = encounter.getServices().size();

for (int i = 0; i < size; i  ) {
    Breakdown breakdown = Breakdown.builder()
            .service(encounter.getServices().get(i))
            .networkRate(createNetworkRate(allowedAmt, discountAmt))
            .build();
    listBreakdown.add(breakdown);
}
return listBreakdown;


List<Breakdown> listBreakdown = encounter.getServices().stream()
        .forEach()
        .map(this::createBreakdown())
        .collect(Collectors.toList());


private Breakdown createBreakdown() {
     Return Breakdown.builder()
             .service(encounter.getServices().get(i))
             .networkRate(createNetworkRate(networkAllowedAmt, networkDiscountAmt))
             .build();
}

CodePudding user response:

Should be like this

List<Breakdown> listBreakdown = encounter.getServices().stream()
        .map(this::createBreakdown)
        .collect(Collectors.toList());

private Breakdown createBreakdown(Service service) {
     return Breakdown.builder()
             .service(service)
             .networkRate(createNetworkRate(networkAllowedAmt, networkDiscountAmt))
             .build();
}

CodePudding user response:

This is what I end up getting - no need for use of stream() in this scenario.

private List<Breakdown> createBreakdownList(final Encounter encounter, final Amount allowedAmt, final Amount discountAmt) {
List<Breakdown> listBreakdown = new ArrayList<>();
        encounter.getServices()
                .forEach(service -> {
                    listBreakdown.add(createBreakdown(service, allowedAmt, discountAmt));
                });
        return listBreakdown;
    }

    private Breakdown createBreakdown(final Service service, final Amount allowedAmt, final Amount discountAmt) {
        return Breakdown.builder()
                .service(service)
                .rate(createRate(allowedAmt, discountAmt))
                .build();
    }
  • Related