Skip to content

Instantly share code, notes, and snippets.

@esuomi
Created February 15, 2014 12:53
Show Gist options
  • Save esuomi/9018946 to your computer and use it in GitHub Desktop.
Save esuomi/9018946 to your computer and use it in GitHub Desktop.
Java 8 lambda syntax and then some to reinvent the FizzBuzz wheel.
package features;
import java.util.function.Function;
import java.util.stream.IntStream;
/**
* Just to prove that I'm not an idiot. Or maybe I am but haven't noticed it yet. Making seemingly simple tasks
* makes one really, really paranoid.
*
* @since 15.2.2014
*/
public class FizzBuzz8 {
public static void main(String[] args) {
/* overfunctionalized, don't actually do this - I did this to test out
- Optional chaining (not possible)
- hiding if..elses (not possible due to above reason, ternary to res...mess things up)
- hiding plain functions (only af.andThen(bf) available)
*/
Function<Integer, Boolean> fizz = (i) -> i % 3 == 0;
Function<Integer, Boolean> buzz = (i) -> i % 5 == 0;
Function<Integer, String> message = (Integer i) ->
i + " => " + (fizz.apply(i)
? (buzz.apply(i) ? "FizzBuzz" : "Fizz")
: (buzz.apply(i) ? "Buzz" : ""));
printWith(message);
// what you really should have in production code; don't split it, clump it together, be reasonable
Function<Integer, String> fizzBuzz = (i) -> {
String msg = "";
if (i % 3 == 0) msg += "Fizz";
if (i % 5 == 0) msg += "Buzz";
if (msg.isEmpty()) msg = Integer.toString(i);
return msg;
};
printWith(fizzBuzz);
}
private static void printWith(Function<Integer, String> message) {
IntStream
.range(1, 100)
.boxed()
.map( message::apply )
.forEach( System.out::println );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment