Skip to content

Instantly share code, notes, and snippets.

@ptiringo
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptiringo/9719884 to your computer and use it in GitHub Desktop.
Save ptiringo/9719884 to your computer and use it in GitHub Desktop.
JavaでStream APIを使ってFizzBuzzする(インデックス表示あり)
package fizzbuzz;
import java.util.stream.Stream;
public class FizzBuzzWriter {
public static void main(String[] args) {
// FizzBuzzの無限リスト
Stream<FizzBuzz> fizzbuzz = Stream.iterate(new FizzBuzz(0), fb -> {
fb.setIndex(fb.getIndex() + 1);
return fb;
}).map(fb -> {
fb.setWord(
(fb.getIndex() % 15 == 0) ? "Fizbuzz" :
(fb.getIndex() % 3 == 0) ? "Fizz" :
(fb.getIndex() % 5 == 0) ? "Buzz" :
Integer.toString(fb.getIndex()));
return fb;
});
// skipが起点、limitが表示数に対応する
fizzbuzz.skip(1).limit(100).forEach(fb ->
System.out.printf("%d:%s%s",
fb.getIndex(),
fb.getWord(),
System.lineSeparator()));
}
static class FizzBuzz {
private int index;
private String word;
public FizzBuzz(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment