10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java8 Stream でズンドコ

Last updated at Posted at 2016-03-12

Java8 ストリーム脳だけど Window がスマートに書けない苦しみ…
最終出力は手抜きになったけど大丈夫だ問題ない

public class ZundokoCheckerWithJava8Stream {
	public static void main(String[] args) {
		final Window<String> window = new Window<>(5);

		Stream.generate(() -> Math.random() <= 0.5 ? "ズン" : "ドコ")
			.map(window::next)
			.peek(System.out::println)
			.filter(z -> z.isPresent() && String.join(",", z.get()).equals("ズン,ズン,ズン,ズン,ドコ"))
			.findFirst();
		System.out.println("キ・ヨ・シ!");
	}

	public static class Window<T> {
		final int size;
		final List<T> elements;

		public Window(int size) {
			this.size = size;
			elements = new ArrayList<>();
		}

		public Optional<List<T>> next(T element) {
			while (wakuwoakeru())
				;
			elements.add(element);
			return peek();
		}

		private boolean wakuwoakeru() {
			if (elements.size() < size) {
				return false;
			}

			elements.remove(0);
			return true;
		}

		public Optional<List<T>> peek() {
			if (elements.size() < size) {
				return Optional.empty();
			}
			return Optional.of(elements);
		}
	}
}
出力例
Optional.empty
Optional.empty
Optional.empty
Optional.empty
Optional[[ドコ, ドコ, ドコ, ドコ, ズン]]
Optional[[ドコ, ドコ, ドコ, ズン, ズン]]
Optional[[ドコ, ドコ, ズン, ズン, ズン]]
Optional[[ドコ, ズン, ズン, ズン, ドコ]]
Optional[[ズン, ズン, ズン, ドコ, ズン]]
Optional[[ズン, ズン, ドコ, ズン, ズン]]
Optional[[ズン, ドコ, ズン, ズン, ズン]]
Optional[[ドコ, ズン, ズン, ズン, ズン]]
Optional[[ズン, ズン, ズン, ズン, ズン]]
Optional[[ズン, ズン, ズン, ズン, ドコ]]
キ・ヨ・シ!
10
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?