0
votes

I was just writing this little code to find the cheapest offer out of a list and I'm wondering if this could be written more elegant with some lambda-function?

private Offer getBestOffer(List<Offer> allOffers, int amount) {
    Offer bestOffer = null;
    BigDecimal bestPrice = null;
    for (Offer offer : allOffers) {

        BigDecimal unitCosts = offer.getUnitPrice().multiply(new BigDecimal(amount));
        BigDecimal completePrice = offer.getBasicCosts().add(unitCosts);

        if (bestPrice == null || completePrice.compareTo(bestPrice) == -1) {
            bestOffer = offer;
            bestPrice = completePrice;
        }
    }
    return bestOffer;
}

Or is this not really a good use case for a lambda-function?

1

1 Answers

1
votes

You could create a custom Comparator with this logic, and then stream the allOffers list and get its minimum according to that Comparator:

private static Offer getBestOffer(List<Offer> allOffers, int amount) {
    Comparator<Offer> cmp =
        Comparator.comparing(o -> 
            o.getBasicCosts().add(o.getUnitPrice().multiply(new BigDecimal(amount))));

    return allOffers.stream().min(cmp).orElse(null);
}