scala foreach usage

1: Use foreach on an array of strings

 val mylist = Array("a1","b2","c3")
 mylist.foreach(arg=>println(arg))   
 2: use foreach on linked lists

 val words:List[Int] = List(1,2,3,4,5)
 words.foreach(word=>println(word))

3: Use foreach on the collection Set

    val s:Set[Int] = Set(1,2,3)
    s.foreach(si=>println(si))

4: Use foreach on Map

    val m:Map[String,String]=Map("a"->"aa","b"->"bb")
    m.foreach(mi=>println(mi))

print result:

(a,aa)
(b,bb)

If you want to add elements to the Map:

m +=("c"->"cc") and the val m form cannot be used when the variable m is defined earlier, only the var m form can be used. The deletion of elements in the Map is currently

5: Use foreach on tuples

The elements in a tuple in scala are immutable, and there can only be a maximum of 22 tuples that can hold different element objects. Although the elements in the tuple are immutable, the content of the object can be changed when the element is an object, see the following example:

    class ClsTmp{
      var i:Int=2
    }
    val ct = new ClsTmp()
    val t=(1,"abc",'d',Console,ct) //Console is the console object
    t.productIterator.foreach(it= >println(it))
    val ctt:ClsTmp = t._5 //t._5 represents the 5th element in the tuple t, the tuple limit can only have up to 22 elements, if it exceeds
    ctt.i = 4
    println(ctt.i)
    ct.i=3
    println(ct.i)
    println(ctt.i)

print result:

1
abc
d
scala.Console$@7530d0a
ForeachTest$ClsTmp$1@27bc2616
4
3
3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325153031&siteId=291194637