Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- import java.util.stream.Stream;
- /**
- *
- * @author toffe boy Aamir
- */
- public class Funktional_level_2 {
- private static final BigDecimal DISCOUNT_VALUE = BigDecimal.valueOf(0.9);
- public static ArrayList GiveMePriceList() {
- final int PRICE_LIST_LIMIT = 25;
- final ArrayList<BigDecimal> PriceList = new ArrayList<>(PRICE_LIST_LIMIT);
- Stream.generate(() -> new Random().nextInt(100)).limit(PRICE_LIST_LIMIT).
- map(BigDecimal::valueOf).
- forEach(PriceList::add);
- return PriceList;
- }
- public static void main(String[] args) {
- final List<BigDecimal> PRICE_LIST = GiveMePriceList();
- //lets total the price > than 30, discounted by 10%
- //old and low level way
- BigDecimal totalDiscount = BigDecimal.ZERO;
- for (BigDecimal price : PRICE_LIST) {
- if (price.compareTo(BigDecimal.valueOf(30)) > 0) {
- BigDecimal calculatedDiscount = price.multiply(DISCOUNT_VALUE);
- totalDiscount = totalDiscount.add(calculatedDiscount);
- }
- }
- System.out.println("Total Discounted Price = " + totalDiscount);
- //New and better way
- // * Free of low level
- // * Easy to Read, Change and Enhance
- // * No Reassigment
- // * Lazy Evaluation
- // * Easy to parallelize
- BigDecimal totalDiscountPrice = PRICE_LIST.stream().filter(price -> price.compareTo(BigDecimal.valueOf(30)) > 0).
- map(price -> price.multiply(DISCOUNT_VALUE)).
- reduce(BigDecimal.ZERO, BigDecimal::add);
- System.out.println("Total Discounted Price = " + totalDiscountPrice);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment