public class FizzBuzzEtc static Integer String condition Predicate Int

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class FizzBuzzEtc {
static F<Integer, String> condition(Predicate<Integer> p, String t) {
return n -> p.test(n) ? t : "";
}
static F<Integer, String> fizz = condition(n -> (n % 3) == 0, "fizz");
static F<Integer, String> buzz = condition(n -> (n % 5) == 0, "buzz");
static F<Integer, String> bang = condition(n -> (n % 7) == 0, "bang");
static F<Integer, String> tryConditions(F<Integer, String>...conditions) {
return n -> {
return defaultIfEmpty(
join(of(conditions).map(c -> c.apply(n)).collect(toList())), valueOf(n));
};
}
public static void main(String[] argv) {
F<Integer, String> fizzbuzz = tryConditions(fizz, buzz);
F<Integer, String> buzzfizz = tryConditions(buzz, fizz);
F<Integer, String> fizzbuzzbang = tryConditions(fizz, buzz, bang);
out.println("FIZZBUZZ:");
range(1, 100).boxed().map(fizzbuzz).forEach(out::println);
out.println("\nBUZZFIZZ:");
range(1, 100).boxed().map(buzzfizz).forEach(out::println);
out.println("\nFIZZBUZZBANG:");
range(1, 106).boxed().map(fizzbuzzbang).forEach(out::println);
}
}