contributed by < jeffrey.w
>
Java 1.8
新增了幾個 feature,其中一些對於提升程式可讀性很有幫助,例如 stream
, lambda expression
, method references
和 functional interface
。
stream operations
會組成一個 stream pipeline
,stream pipeline
包含了一個 source
、零個或一個以上的 intermediate operations
(例如 filter
),還有一個 terminal operation
(例如 forEach
) [1
]。
intermediate operations
是指像 filter
、map
、distinct
之類的 method,這些 method 會將一個 stream
轉換成另一個 stream
[1
]。
filter
是一個 intermediate operations
,第 11 行的 filter
會讓符合條件 (p < 3) 的 elements 保留下來並返回新的 stream
,在這個新的 stream
裡,每一個 element 都會符合第 11 行的條件。
如果要對一個 collection 取一個 distinct 的集合,用 for 硬寫雖然也寫得出來,但是用 distinct
這個 intermediate operations
,可以寫出更簡潔更優雅的 code,像第 11 行
{1, 2, 3, 3} 經過 stream
再經過 distinct
,就是 {1, 2, 3}
使用 Lambda expression
的時機,Oracle
的 The Java™ Tutorials
有列出 9 種理想的 use case [2
]。以下針對這 9 種情境實驗一下
第 6 行的寫法就比用 for(String str : args)
更容易看出意圖
第 8 行的 p -> checker.test(p)
就比 p -> Integer.valueOf(p) >= 1 && Integer.valueOf(p) < 18
容易維護。未來要修改也比較容易,換掉第 4 行的 implementation
就可以了。
第 4 行的 Checker checker = new Checker() {..
是使用 anonymous class
第 3~5 行結合 functional interface 和 lambda expression
9.6.4.9. @FunctionalInterface
9.8. Functional Interfaces
Annotation Type FunctionalInterface
java8
java 8
stream
lambda expression