iamaamir

Functional java level 2

Aug 7th, 2015
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1.  
  2.  
  3. import java.math.BigDecimal;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Random;
  7. import java.util.stream.Stream;
  8.  
  9. /**
  10.  *
  11.  * @author toffe boy Aamir
  12.  */
  13. public class Funktional_level_2 {
  14.  
  15.     private static final BigDecimal DISCOUNT_VALUE = BigDecimal.valueOf(0.9);
  16.  
  17.     public static ArrayList GiveMePriceList() {
  18.         final int PRICE_LIST_LIMIT = 25;
  19.         final ArrayList<BigDecimal> PriceList = new ArrayList<>(PRICE_LIST_LIMIT);
  20.  
  21.         Stream.generate(() -> new Random().nextInt(100)).limit(PRICE_LIST_LIMIT).
  22.                 map(BigDecimal::valueOf).
  23.                 forEach(PriceList::add);
  24.  
  25.         return PriceList;
  26.     }
  27.  
  28.     public static void main(String[] args) {
  29.  
  30.         final List<BigDecimal> PRICE_LIST = GiveMePriceList();
  31.  
  32.         //lets total the price > than 30, discounted by 10%
  33.        
  34.         //old and low level way
  35.         BigDecimal totalDiscount = BigDecimal.ZERO;
  36.         for (BigDecimal price : PRICE_LIST) {
  37.             if (price.compareTo(BigDecimal.valueOf(30)) > 0) {
  38.                 BigDecimal calculatedDiscount = price.multiply(DISCOUNT_VALUE);
  39.                 totalDiscount = totalDiscount.add(calculatedDiscount);
  40.             }
  41.         }
  42.  
  43.         System.out.println("Total Discounted Price = " + totalDiscount);
  44.  
  45.         //New and better way
  46.         // * Free of low level
  47.         // * Easy to Read, Change and Enhance
  48.         // * No Reassigment
  49.         // * Lazy Evaluation
  50.         // * Easy to parallelize
  51.         BigDecimal totalDiscountPrice = PRICE_LIST.stream().filter(price -> price.compareTo(BigDecimal.valueOf(30)) > 0).
  52.                 map(price -> price.multiply(DISCOUNT_VALUE)).
  53.                 reduce(BigDecimal.ZERO, BigDecimal::add);
  54.         System.out.println("Total Discounted Price = " + totalDiscountPrice);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment