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.
CodePudding user response:
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.
CodePudding user response:
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 everyFees
with theiramountFee
findFirst
function will do the same job asbreak;
and will return on the first match.orElse
if there is no match I kept the samebaseFee
value
The 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.