From 4262461c3ce6ef747a1c4d1083bbfeed97900ef9 Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Wed, 15 May 2019 15:23:54 -0300 Subject: [PATCH] Trying some function composition, but it is not working --- .gitignore | 2 ++ Compo.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 .gitignore create mode 100644 Compo.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..55175ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.class +*.sw? diff --git a/Compo.java b/Compo.java new file mode 100644 index 0000000..027070a --- /dev/null +++ b/Compo.java @@ -0,0 +1,45 @@ +/* + * This is me testing function composition in Java. + * + */ +import java.util.List; +import java.util.stream.Stream; +import java.util.stream.Collectors; +import java.util.function.Function; +import java.util.function.Consumer; + +public class Compo { + public static void main(String[] argv) { + System.out.println("Starting up..."); + + Doubler doubler = new Doubler(); + PlusTwo plusTwo = new PlusTwo(); + Printer printer = new Printer(); + + List result = Stream.of(2L, 4L, 5L, 7L) + .peek(doubler.andThen(plusTwo).andThen(printer)) + .collect(Collectors.toList()); + System.out.println("Result: " + result); + } + + private static class Doubler implements Function { + @Override + public Long apply(Long input) { + return input * 2; + } + } + + private static class PlusTwo implements Function { + @Override + public Long apply(Long input) { + return input + 2L; + } + } + + private static class Printer implements Consumer { + @Override + public void accept(Long input) { + System.out.println("Consumer: " + input); + } + } +}