LoginSignup
3
2

More than 5 years have passed since last update.

Java8のStreamの出力をGroovyで覗いてみる

Last updated at Posted at 2016-10-24

TL;DR

Java8のStreamの遅延評価を直接覗いてみる。それだけ。

thanks for

ラムダ使えますか?ゆるふわJava8入門
(Java8のStreamをよく使うインタフェースとメソッドに絞って解説してもらった)

[Groovy]GroovyからJava8のstreamを利用する。
(GroovyでStream使う方法はこちらから)

必要物

  • Groovy
  • groovyshの対話環境が動く何か

Stream化

GroovyでのList表現

(1..10)
//===> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ListをStream化する

※StreamはListにJavaのメソッドを作用させるための下準備。

(1..10).stream()
//===> java.util.stream.ReferencePipeline$Head@43b9fd5

なにやらオブジェクト化された。

ListのStream化を解除する

collect()メソッドを使う。

(1..10).stream().collect()
//===> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

これで中身が見れる。lamdaの世界では終端処理と言うらしい。
collect()を噛ませて初めて式が評価されるので、遅延評価になっている。

Filter

Filterを掛ける

(1..10).stream().filter{ it % 2 == 0 }
//===> java.util.stream.ReferencePipeline$2@1b84f475

(1..10).stream().filter{ it % 2 == 0 }.collect()
//===> [2, 4, 6, 8, 10]

2でmodとって0になる物だけfilterできた。

Map

各々に写像(map)を噛ませる

(1..10).stream().map{ it -> it + 1 }
//===> java.util.stream.ReferencePipeline$3@53de625d

(1..10).stream().map{ it -> it + 1 }.collect()
//===> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

関数の連鎖

Filter & Map

(1..10).stream().filter{ it % 2 == 0 }.map{ it -> it + 1 }
//===> java.util.stream.ReferencePipeline$3@289710d9

(1..10).stream().filter{ it % 2 == 0 }.map{ it -> it + 1 }.collect()
//===> [3, 5, 7, 9, 11]

collect()で終端処理をして初めて値が評価される。

3
2
0

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
3
2