Last active
August 29, 2015 13:57
-
-
Save ptiringo/9719884 to your computer and use it in GitHub Desktop.
JavaでStream APIを使ってFizzBuzzする(インデックス表示あり)
This file contains 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
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