天天看點

Scala中的foreach forall exists map函數及其差別

forall

對集合中的元素進行某個判斷,全部為true則傳回true,反之傳回false。

例如:

scala> var s = List("hello", "world")
s: List[String] = List(hello, world)

scala> s.forall( f => f.contains("h") )
res34: Boolean = false

scala> s.forall( f => f.contains("o") )
res35: Boolean = true
           
exists

對集合中的元素進行某個判斷,其中之一符合條件則傳回true,反之傳回false。和forall是一個對應的關系,相當于 and 和 or。

scala> s.exists( f => f.contains("h") )
res36: Boolean = true
           
foreach

對集合中元素進行某種操作,但是傳回值為空,實際上相當于for循環的一個簡寫版。這個看上去比較繞,本來我以為是可以對元素進行某種更改呢,後來發現是了解錯誤的。

scala> s.foreach( f => println(f) )
hello
world

scala> s.foreach( f => f.concat("test") )
scala> s
res39: List[String] = List(hello, world)

scala> var res = s.foreach( f => f.concat("test") )
scala> res

           

同時,我這裡犯了個錯誤:就是List不可變。是以本身List就不會被更改,若想使用可變List,需使用

scala.collection.mutable.ListBuffer.empty[type]

map

對集合中元素進行某個操作,傳回值非空。比較繞,和foreach類似,但是傳回值非空。

scala> s.map( f => f.concat("test") )
res41: List[String] = List(hellotest, worldtest)

scala> s
res42: List[String] = List(hello, world)

scala> var res = s.map( f => f.concat("test") )
res: List[String] = List(hellotest, worldtest)

scala> s
res43: List[String] = List(hello, world)

scala> res
res44: List[String] = List(hellotest, worldtest)
           
參考
  • https://stackoverflow.com/questions/12547235/scala-forall-example
  • https://docs.scala-lang.org/zh-cn/overviews/collections/concrete-mutable-collection-classes.html
  • http://www.runoob.com/scala/scala-collections.html
  • http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/