2015-05-02 29 views

回答

2

最簡單的方法可能是f.map(identity),這並不一定返回List,但適當類型的序列,根據過濾前的原始序列類型。

如果您想嚴格執行List,請將結果轉換爲List之後:f.map(identity).toList

至於差異,對於大多數集合filter立即執行過濾,在內存中構建一個新集合並將其返回,並且withFilter返回一個對象,該對象存儲原始集合並僅在請求元素時執行過濾。

+0

只是它在這種情況下返回一個'Vector'。 – tuxdna

0

您可以使用flatMap

scala> val f = ((2 to 10) withFilter (_ > 5) withFilter(_ < 8)) 
f: scala.collection.generic.FilterMonadic[Int,scala.collection.immutable.IndexedSeq[Int]] = [email protected] 

scala> f.flatMap(List(_)).toList 
res0: List[Int] = List(6, 7) 
+1

這看起來像一個黑客... –

+0

是的,這是monadic hack! 「List」是一個monad,「identity」也是。 – tuxdna

相關問題