Redo foreach to .stream().map

Martin :

currently I have two lists List<MonthlyFeePayment> monthlyFeePaymentList and a new one List<FeePaymentStatusRequest> request = new ArrayList<>();. What I need is to go through all monthlyFeePaymentList elements and fill my request list. FeePaymentStatus consists from monthlyFeePaymentId and sourceSystem(which is always the same).

My current implementation:

List<FeePaymentStatusRequest> request = new ArrayList<>();
    for (MonthlyFeePayment monthlyFeePayment : monthlyFeePaymentList) {
        request.add(new FeePaymentStatusRequest(monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW"));
    }

I want to re do it using .stream().map(), but I can't figure it out. It should be pretty easy considering that it's only two lists. But I don't know which list should go first, request.stream() or monthlyFeePaymentList.stream()? Could you explain how the Stream#map works in this specific situation?

Andronicus :

The one you're iterating over:

List<FeePaymentStatusRequest> request = monthlyFeePaymentList.stream()
    .map(monthlyFeePayment -> new FeePaymentStatusRequest(monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW"))
    .collect(Collectors.toList());

You can collect it then without creating a new list explicitly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164060&siteId=1