Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Can someone re-write this Java 8 Stream?

Options
  • 29-03-2016 4:11pm
    #1
    Closed Accounts Posts: 6,075 ✭✭✭


        public long getDiscountedPrice(Discount... discounts) {
    
            long discountSum = stream(discounts)
                    .mapToLong(d -> d.discount(unmodifiableList(items)))
                    .sum();
            return totalPrice - discountSum;
        }
    
    public interface Discount {
    
        BigDecimal discount(List<String> items);
    }
    

    Currently, d.discount() returns a float. I want to change it to return BigDecimal because it's currency. Can someone help me rewritd this method? I'm new to Java 8.


Comments

  • Closed Accounts Posts: 6,075 ✭✭✭IamtheWalrus


    Or even in Java 6?


  • Closed Accounts Posts: 6,075 ✭✭✭IamtheWalrus


    Java 2?


  • Registered Users Posts: 8,800 ✭✭✭Senna


    I'm only learning java so my help is limited and you probably know a lot more that me, but....

    Is this code working as a long (similar to float) at the moment? If it is then the discountSum variable is working as a long when it's taking in a BigDecimal, without the need to cast.

    The return type of getDiscountPrice is a long.
    In the method you have discountSum declared also as a long.
    By changing both of those to BigDecimal would be a start, but as I'm unfamiliar with BigDecimal I'm not sure if it's that easy.


  • Closed Accounts Posts: 6,075 ✭✭✭IamtheWalrus


    private BigDecimal itemsDiscountFor(Discount[] discounts) {
            return stream(discounts)
                    .map(d -> d.discount(unmodifiableList(items)))
                    .reduce(ZERO, BigDecimal::add);
        }
    


Advertisement