Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.function.Consumer;
  4. import java.util.function.Function;
  5. import java.util.stream.Collectors;
  6.  
  7. /**
  8. * Functional replacement for Template Method in java 8
  9. * Created by ton on 25/10/16.
  10. */
  11. public class TemplateMethodFunctional {
  12.  
  13. /**
  14. * Take a conversion function from Double to String, and a consumer of a list of Strings,
  15. * and combine them to create a new consumer that accepts a list of Doubles.
  16. * @param numToLetter a Function from Double to String.
  17. * @param printGradeReport a Consumer for a List of Strings.
  18. * @return a Consumer for a List of Double.
  19. */
  20. private static Consumer<List<Double>> makeGradeReporter( Function<Double, String> numToLetter,
  21. Consumer<List<String>> printGradeReport) {
  22.  
  23. return lst -> printGradeReport.accept(
  24. lst.stream().map(numToLetter)
  25. .collect(Collectors.toList())
  26. );
  27. }
  28.  
  29. /**
  30. * Convert a double from 0.0 to 5.0 to a grade in the range 'A' - 'F'.
  31. * @param grade grade as a Double
  32. * @return the corresponding letter
  33. */
  34. private static String fullGradeConverter(Double grade) {
  35. if (grade <= 5.0 && grade > 4.0)
  36. return "A";
  37. else if (grade <= 4.0 && grade > 3.0)
  38. return "B";
  39. else if (grade <= 3.0 && grade > 2.0)
  40. return "C";
  41. else if (grade <= 2.0 && grade > 1.0)
  42. return "D";
  43. else if (grade <= 1.0 && grade > 0.0)
  44. return "E";
  45. else if (grade == 0.0)
  46. return "F";
  47. else
  48. return "N/A";
  49. }
  50.  
  51. /**
  52. * Consume a List of Strings by printing each one on a new line.
  53. * @param letters
  54. */
  55. private static void simplePrint(List<String> letters) {
  56. letters.stream().forEach(System.out::println);
  57. }
  58.  
  59. public static void main(String[] args) {
  60. List<Double> grades = Arrays.asList(2.0, 2.5, 5.0, 1.0);
  61. Consumer<List<Double>> example = makeGradeReporter(
  62. TemplateMethodFunctional::fullGradeConverter,
  63. TemplateMethodFunctional::simplePrint);
  64.  
  65. example.accept(grades);
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement