Scala Set and foreach

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-10 09:05:23 Viewed : 236


Scala Set and foreach

Creates a set with the specified elements. 

   def apply[A](elems: A*): Set[A] 

set is a collection which only contains unique items

·        Immutable set

val variable_name: Set[type] = Set(item1, item2, item3)

or

val variable_name = Set(item1, item2, item3) 

·        Mutable Set

var variable_name: Set[type] = Set(item1, item2, item3)

or

var variable_name = Set(item1, item2, item3) 

Example:

Following example illustrates about Scala set and foreach

Save the file as −  SetExampleApp.scala. 

SetExampleApp.scala

 package runnerdev 

object SetExampleApp extends App { 

  // Creating empty sets 

  var set = scala.collection.mutable.Set[Int]()

  set.add(1)

  set.add(10)

  // Display the value of myset

  println("The set is:" + set) 

  // Creating and initializing mutable sets

  var set1Set[String] = Set("One""Two""Three""Four""Five")

  println("set1 :" + set1)

  var set2 = Set(102030) 

  println("set2 :" + set2) 

  // Display the value of set2 using a foreach loop

  println(" iterate Set 2:")

  set2.foreach((x: Int) => println(x)) 

  // Creating and initializing immutable sets

  val animalSet = Set("Ant""Bat""Cat""Dog""Elephant")

  animalSet.foreach((xString) => println(x)) 

  // Returns first element present in the set

  println("head" + animalSet.head 

  // Returns all elements except first element. 

  println("tail " + animalSet.tail

  // Returns either true or false 

  println(animalSet.isEmpty)

}

     

compile and run the above example as follows 

scala> scalac SetExampleApp.scala

scala> scala SetExampleApp

Output :

The set is:Set(1, 10)

set1 :Set(One, Five, Two, Four, Three)

set2 :Set(10, 20, 30) 

iterate Set 2:

10

20

30

Bat

Cat

Ant

Dog

Elephant

headBat

tail Set(Cat, Ant, Dog, Elephant)

false

Search
Sub-Categories
Related Articles

Leave a Comment: