Scala Set ,Union and Intersect

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-10 09:13:28 Viewed : 183


Scala Set ,Union and Intersect

Computes the intersection between this set and another set.

def intersect(that: GenSet[Int]): Set[Int]

(OR)

def &(that: GenSet[Int]): Set[Int] 

Computes the union between this set and another set.

def union(that: GenSet[Int]): Set[Int]

 Set API List:


Example:

Following example illustrates about Scala set, union and interection

Save the file as −  SetAppl.scala  

SetAppl.scala 

 package runnerdev 

object SetAppl extends App {

  /**Scala program that uses set, contains*/ 

  // Create a Set of two strings.

  val animals = Set("cat""dog")

  println("animals :" + animals) 

  // See if this string is in the set.

  if (animals.contains("dog"))

    println(true) 

  //Scala program that combines two sets 

  // Create two sets.

  val results1 = Set(124)

  val results2 = Set(235)

  /** "++" operator to combine two sets **/

  val combSet = results1 ++ results2

  println("combSet :" + combSet)

  val combSet1 = results1.union(results2)

  // Display all sets.

  println(results1)

  println(results2)

  println(combSet)

  println(combSet1) 

  // Use intersect to find common elements of two sets.

  val interSec = results1.intersect(results2)

  println("interSec : " + interSec) 

  // Short syntax for intersection.

  val interSec1 = results1 & results2

  println("interSec1: " + interSec1) 

}

    

compile and run the above example as follows 

scala> scalac SetAppl.scala

scala> scala SetAppl 

 Output:

animals :Set(cat, dog)

true

combSet :Set(5, 1, 2, 3, 4)

Set(1, 2, 4)

Set(2, 3, 5)

Set(5, 1, 2, 3, 4)

Set(5, 1, 2, 3, 4)

interSec : Set(2)

interSec1: Set(2)

Search
Sub-Categories
Related Articles

Leave a Comment: