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

3
  • Yes, that is quite possible. And it's not all that difficult. stream -> filter -> findFirst -> if present ... Commented Jan 20, 2023 at 10:08
  • for (ItemDO item : updateItems.getItemsDO().getItems()) how to do if loop given like this @Stultuske. Commented Jan 20, 2023 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. Commented Jan 20, 2023 at 14:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@lokesh598 this does already stop at the first match and return it. No need for a “break” statement
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.