Last active
August 29, 2015 14:14
-
-
Save kariyayo/4256a2b89f68e99d0fb9 to your computer and use it in GitHub Desktop.
Java8のrange
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
/* | |
* IntStreamのrangeメソッド | |
*/ | |
IntStream.range(1, 20); | |
// [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] | |
/* | |
* rangeClosedメソッド。最後が含まれる | |
*/ | |
IntStream.rangeClosed(1, 20); | |
// [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] | |
/* | |
* 1ずつではなく、2ずつ増やしたい場合は無限streamを使うしかなさそう。 | |
* あとtakeWhileもないのでちょっとつらい実装に・・・(takeWhileがないのは並列化できないから?)。 | |
*/ | |
IntStream.iterate(1, x -> x + 2).limit(30).filter(x -> x < 20); | |
// [1,3,5,7,9,11,13,15,17,19] | |
/* | |
* 13の倍数の最初の24個からなるリスト | |
*/ | |
IntStream.iterate(13, x -> x + 13).limit(24) | |
// [13,26,39,52,65,78,91,104,117,130,143,156,169,182,195,208,221,234,247,260,273,286,299,312] | |
/* | |
* 同じ値を繰り返す | |
*/ | |
IntStream.iterate(5, x -> x).limit(5) | |
// [5,5,5,5,5] | |
/* | |
* generateでもできた | |
*/ | |
IntStream.generate(() -> 5).limit(5) | |
// [5,5,5,5,5] | |
/* | |
* リストが要素のStream | |
*/ | |
Stream.generate(() -> Arrays.asList(1, 2, 3)).limit(3) | |
// [[1, 2, 3], [1, 2, 3], [1, 2, 3]] | |
/* | |
* 入れ子になったのを平らにしたいときはreduceを使って1つのリストにする。 | |
* reduceの返り値はStreamオブジェクトではなくListのオブジェクトになるので注意する。 | |
*/ | |
Stream.generate(() -> Arrays.asList(1, 2, 3)) | |
.limit(3) | |
.reduce(new ArrayList<>(), (acc, x) -> { | |
acc.addAll(x); | |
return acc; | |
}) | |
// [1, 2, 3, 1, 2, 3, 1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
スキップするなんてのもありますよ