Skip to content

Instantly share code, notes, and snippets.

@tonvanbart
Last active October 25, 2016 21:19
Show Gist options
  • Save tonvanbart/61f813c2aef3ab3c81728241ef0a86e2 to your computer and use it in GitHub Desktop.
Save tonvanbart/61f813c2aef3ab3c81728241ef0a86e2 to your computer and use it in GitHub Desktop.
Functional programming example in java8: replace template method pattern with function composition.
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Functional replacement for Template Method in java 8
* Created by ton on 25/10/16.
*/
public class TemplateMethodFunctional {
/**
* Take a conversion function from Double to String, and a consumer of a list of Strings,
* and combine them to create a new consumer that accepts a list of Doubles.
* @param numToLetter a Function from Double to String.
* @param printGradeReport a Consumer for a List of Strings.
* @return a Consumer for a List of Double.
*/
private static Consumer<List<Double>> makeGradeReporter( Function<Double, String> numToLetter,
Consumer<List<String>> printGradeReport) {
return lst -> printGradeReport.accept(
lst.stream().map(numToLetter)
.collect(Collectors.toList())
);
}
/**
* Convert a double from 0.0 to 5.0 to a grade in the range 'A' - 'F'.
* @param grade grade as a Double
* @return the corresponding letter
*/
private static String fullGradeConverter(Double grade) {
if (grade <= 5.0 && grade > 4.0)
return "A";
else if (grade <= 4.0 && grade > 3.0)
return "B";
else if (grade <= 3.0 && grade > 2.0)
return "C";
else if (grade <= 2.0 && grade > 1.0)
return "D";
else if (grade <= 1.0 && grade > 0.0)
return "E";
else if (grade == 0.0)
return "F";
else
return "N/A";
}
/**
* Consume a List of Strings by printing each one on a new line.
* @param letters
*/
private static void simplePrint(List<String> letters) {
letters.stream().forEach(System.out::println);
}
public static void main(String[] args) {
List<Double> grades = Arrays.asList(2.0, 2.5, 5.0, 1.0);
Consumer<List<Double>> example = makeGradeReporter(
TemplateMethodFunctional::fullGradeConverter,
TemplateMethodFunctional::simplePrint);
example.accept(grades);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment