Home » Scala language

Set &() method In Scala

The Set &() method in Scala is used to initialize a new in Scala using two sets. In this tutorial, we will learn about &() method for the initialization of sets and examples.
Submitted by Shivang Yadav, on December 05, 2019

The Set &() method in Scala

The &() method in the Set is used to create a new set in Scala. This new set created contains all elements from the other two sets that are common for both of the given sets i.e. new set created is the intersection of two sets.

Syntax:

    set1.&(set2)

parameter(s):

  • set2 – It represents the set for the intersection.

Return value:

It returns a new set that has all elements of both the sets.

Let's see a few examples, for the usage of this function,

Case 1: When both sets have common elements.

object myObject
{ 
	def main(args:Array[String]) 
	{ 
		val set1 = Set(13, 89, 57, 23, 96)
		println("Set1 : "+ set1)
		val set2 = Set(01, 90, 13, 54, 89, 234, 54)
		println("Set2 : "+ set2)
		val set3 = set1.&(set2)
		println("The intersection of two sets : "+ set3)
	} 
} 

Output

Set1 : HashSet(57, 89, 96, 13, 23)
Set2 : HashSet(234, 13, 54, 90, 89, 1)
The intersection of two sets : HashSet(89, 13)

Case 2: When sets donot have common elements

object myObject
{ 
	def main(args:Array[String]) 
	{ 
		val set1 = Set(13, 89, 57, 23, 96)
		println("Set1 : "+ set1)
		val set2 = Set(01, 90, 54, 234, 54)
		println("Set2 : "+ set2)
		val set3 = set1.&(set2)
		println("The intersection of two sets : "+ set3)
	} 
} 

Output

Set1 : HashSet(57, 89, 96, 13, 23)
Set2 : Set(1, 90, 54, 234)
The intersection of two sets : HashSet()



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.