天天看点

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/