Last active
August 29, 2015 14:23
-
-
Save YusukeHosonuma/a0a3c509f11bff4e1952 to your computer and use it in GitHub Desktop.
Java8でFizzBuzz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.stream.Stream; | |
public class FizzBuzzSample { | |
public static void main(String[] args) { | |
// Stream.iterateを使用して自然数(の無限数列)のストリームを用意 | |
Stream<Integer> naturalNumbers = Stream.iterate(1, integer -> integer + 1); | |
// 自然数(の無限数列)をfizzBuzzメソッド(参照)を利用して文字列のストリームに変換 | |
Stream<String> fizzBuzz = naturalNumbers.map(FizzBuzzSample::fizzBuzz); | |
// 文字列のストリームから先頭20件を取得して、それぞれ標準出力 | |
fizzBuzz.limit(20).forEach(s -> System.out.println(s)); | |
} | |
// FizzBuzzメソッド | |
private static String fizzBuzz(Integer i) { | |
return (i % 15 == 0) ? "FizzBuzz" | |
: (i % 3 == 0) ? "Fizz" | |
: (i % 5 == 0) ? "Buzz" | |
: String.valueOf(i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment