fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.*;
  7. import java.util.function.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. Stream<String> fizz = pattern(3, "Fizz");
  15. Stream<String> buzz = pattern(5, "Buzz");
  16. Stream<String> pattern = zip((a, b) -> a + b, fizz, buzz);
  17. Stream<String> fizzbuzz = zip((n, p) -> p.isEmpty() ? ""+n : p, nums().boxed(), pattern);
  18. fizzbuzz.limit(100).forEach(System.out::println);
  19. }
  20.  
  21. static IntStream nums() {
  22. return IntStream.iterate(1, i -> i + 1);
  23. }
  24. static Stream<String> pattern(int n, String pattern) {
  25. return nums().mapToObj(i -> i % n == 0 ? pattern : "");
  26. }
  27.  
  28. static <T, U, R> Stream<R> zip(BiFunction<T, U, R> zipper, Stream<T> ts, Stream<U> us) {
  29. Iterator<T> tsItr = ts.iterator();
  30. Iterator<U> usItr = us.iterator();
  31. Iterator<R> iterator = new Iterator<R>() {
  32. public boolean hasNext() {
  33. return tsItr.hasNext() && usItr.hasNext();
  34. }
  35. public R next() {
  36. return zipper.apply(tsItr.next(), usItr.next());
  37. }
  38. };
  39.  
  40. return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
  41. }
  42. }
Success #stdin #stdout 0.09s 711680KB
stdin
Standard input is empty
stdout
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz