Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement