Scala Set and foreach

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2020-10-10 03:35:23 Viewed : 655


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

In Scala, a Set is a collection that represents an unordered collection of unique elements. Set does not allow duplicate elements, and it provides efficient operations for checking membership and adding/removing elements. The foreach method is used to iterate over the elements of a Set and perform an action on each element. Here is an overview of Set and how to use foreach:

1. Creating a Set:

You can create a Set in Scala using various methods:

  • Using Set() constructor:

    scala
    val mySet = Set(1, 2, 3, 4, 5)
  • Using the + operator to add elements:

    scala
    val mySet2 = Set(1, 2, 3) + 4 + 5

2. Iterating Over a Set (Using foreach):

The foreach method allows you to iterate over the elements of a Set and perform an action on each element:

scala
mySet.foreach { element => println(s"Element: $element") }

3. Common Set Operations:

  • Adding and Removing Elements:

    scala
    val updatedSet = mySet + 6 // Adds an element (6) to the set val removedSet = mySet - 3 // Removes an element (3) from the set
  • Checking Membership:

    scala
    val containsElement = mySet.contains(4) // Checks if an element (4) is in the set
  • Set Operations (Union, Intersection, Difference):

    scala
    val set1 = Set(1, 2, 3) val set2 = Set(3, 4, 5) val union = set1.union(set2) // Union of two sets val intersection = set1.intersect(set2) // Intersection of two sets 
    val difference = set1.diff(set2) // Set differencee

4. Immutability:

Set is an immutable collection, meaning you cannot modify its elements. Instead, you create new sets when performing operations.

Here is a complete example:

scala
val mySet = Set(1, 2, 3, 4, 5) mySet.foreach { element => println(s"Element: $element") } val updatedSet = mySet + 6 val removedSet = mySet - 3 val containsElement = mySet.contains(4) println(s"Updated Set: $updatedSet") println(s"Removed Set: $removedSet") println(s"Contains 4: $containsElement")

This code creates a Set, iterates over its elements using foreach, adds an element to the set, removes an element from the set, and checks for the presence of an element. It demonstrates basic operations with Set and how to use foreach for iteration.


Here are examples of working with Scala Set collections and using the foreach method, along with explanations and their respective outputs:

1. Creating a Set:

scala
val mySet = Set(1, 2, 3, 4, 5)

In this example, we create a Set named mySet containing integers from 1 to 5.

2. Iterating Over a Set (Using foreach):

scala
mySet.foreach { element => println(s"Element: $element") }

This code iterates over the elements of mySet using foreach and prints each element.

3. Common Set Operations:

  • Adding and Removing Elements:
scala
val updatedSet = mySet + 6 // Adds an element (6) to the set val removedSet = mySet - 3 // Removes an element (3) from the set

Here, we create updatedSet by adding an element (6) to mySet and removedSet by removing an element (3) from mySet.

  • Checking Membership:
scala
val containsElement = mySet.contains(4) // Checks if an element (4) is in the set

This code checks if the element 4 is present in mySet and stores the result in containsElement.

4. Immutability:

Set is an immutable collection, so all these operations create new sets rather than modifying the existing one.

Here is the complete code with outputs:

scala
val mySet = Set(1, 2, 3, 4, 5) mySet.foreach { element => println(s"Element: $element") } val updatedSet = mySet + 6 val removedSet = mySet - 3 val containsElement = mySet.contains(4) println(s"Updated Set: $updatedSet") println(s"Removed Set: $removedSet") println(s"Contains 4: $containsElement")

Output:

mathematica
Element: 1 Element: 2 Element: 3 Element: 4 Element: 5 Updated Set: Set(1, 2, 3, 4, 5, 6) Removed Set: Set(1, 2, 4, 5) Contains 4: true

In this example, we create a Set, iterate over its elements using foreach, add an element, remove an element, and check for the presence of an element. It demonstrates basic operations with Set and how to use foreach for iteration.

Search
Related Articles

Leave a Comment: