for(Fees fee : feeList) {
if(fee.getType().equalsIgnoreCase(feeType)) {
baseFee = fee.getAmountFee();
break;
}
}
I wanted to know if it's possible to convert the above example to a single stream where there is a for loop.
for(Fees fee : feeList) {
if(fee.getType().equalsIgnoreCase(feeType)) {
baseFee = fee.getAmountFee();
break;
}
}
I wanted to know if it's possible to convert the above example to a single stream where there is a for loop.
Certainly, you can convert it as follows:
Optional<Double> optionFeeAmount = feeList
.stream()
.filter(fee -> feeType.equalsIgnoreCase(fee.getType()))
.findFirst()
.map(Fees::getAmountFee);
You can add orElse(0)
at the end, if you want to return 0 as a default result. Also you can use findAny()
if the sequence in list doesn't matter.
Yes possible, something like:
baseFee = feeList.stream().filter(fee -> fee.getType().equalsIgnoreCase(feeType))
.map(Fees::getAmountFee)
.findFirst()
.orElse(baseFee);
Solution explanation:
filter
function replace the if conditionmap
function will replace every Fees
with their amountFee
findFirst
function will do the same job as break;
and will return on the first match.orElse
if there is no match I kept the same baseFee
valueThe stream API (functional programming) is smart enough in performance meaning that it will not filter everything and then do the map, instead it will do it in its way, with good performance.