Home > Software design >  How to convert loop into stream, to this java code snippet
How to convert loop into stream, to this java code snippet

Time:01-20

 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 condition
  • map 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 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.

  • Related