-1
 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.

Holger
  • 285,553
  • 42
  • 434
  • 765
lokesh598
  • 1
  • 1
  • Yes, that is quite possible. And it's not all that difficult. stream -> filter -> findFirst -> if present ... – Stultuske Jan 20 '23 at 10:08
  • for (ItemDO item : updateItems.getItemsDO().getItems()) how to do if loop given like this @Stultuske. – lokesh598 Jan 20 '23 at 14:20
  • SO is not about handing you custom code. We either put you on the right path, or, if you've already tried, help you correct your code. So far, I haven't even seen you attempt to create a Stream. – Stultuske Jan 20 '23 at 14:23

2 Answers2

0

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.

VaibS
  • 1,627
  • 1
  • 15
  • 21
  • 1
    @lokesh598 this does already stop at the first match and return it. No need for a “break” statement – Holger Jan 20 '23 at 13:15
0

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.

Houari Zegai
  • 98
  • 1
  • 10