Refactoring for DRY (original) (raw)

Barry Burd bburd at drew.edu
Tue Apr 9 13:55:12 PDT 2013


How's this version (of a simple example to introduce some of the functional programming concepts)? Note: I'm not using type inference because my readers are better off learning about that later. Also, I'm using System.out.println in order to have a complete, self-contained example, but I'm saving that System.out.println call to the very end to avoid mixing side-effects with the functional code.

import java.text.NumberFormat; import java.util.ArrayList;

public class TallySales {

ArrayList sales = new ArrayList(); NumberFormat currency = NumberFormat .getCurrencyInstance();

public static void main(String[] args) { new TallySales(); }

TallySales() { fillArray(sales); System.out.println(currency.format(sales.stream().map((Sale sale) -> sale.getPrice()).reduce((Double price1, Double price2) -> price1 + price2).get())); }

private void fillArray(ArrayList sales) { sales.add(new Sale("DVD", 15.00, true)); sales.add(new Sale("Book", 12.00, false)); sales.add(new Sale("DVD", 21.00, true)); sales.add(new Sale("Magazine", 5.25, true)); } }



More information about the lambda-dev mailing list