Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Can someone re-write this Java 8 Stream?

  • 29-03-2016 03: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, Registered Users 2 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