Scala Sets | Learn About Sets in Scala Collections

Scala course with real-time projects Start Now!!

In this Scala Sets tutorial, we will learn about sets, how to define Scala Sets, how to process them, and what methods to call on sets in Scala. We will also learn Declaring a set, Operations on sets in Scala collections, Concatenating Sets, Max and Min in a Scala set, and Finding Values common to two sets in Scala.

So, let’s start the discussion on Scala Sets.

An Introduction to Sets in Scala

A Scala Set is a collection that won’t take duplicates. By default, Scala uses immutable sets. But if you want, you can import the scala.collection.mutable.Set class. To be able to refer to both of these in the same collection, we can refer to the immutable set as Set and the mutable set as mutable.Set. You can also learn Scala Array from our tutorial, once you are done with Scala sets.

Declaring a Set in Scala

You can either declare an empty set in Scala or one with values.

a. Declaring an Empty Set

We must include the type annotation when declaring an empty set, so it can be decided what concrete type to assign to a variable.

scala> var s:Set[Int]=Set()
s: Set[Int] = Set()

b. Declaring a Set with Values

We may choose to elide the type annotation. When we do so, Scala will infer that from the type of values inside the set.

scala> var s=Set(1,4,4,3)
s: scala.collection.immutable.Set[Int] = Set(1, 4, 3)
scala> var s:Set[Int]=Set(1,4,4,3)
s: Set[Int] = Set(1, 4, 3)

Note that this does not rearrange values as {1,3,4} as Python would do.

Operations on Scala Sets

Scala has the following three operations on a set:

a. head

This will return the first element of a Scala set.

scala> s.head
res0: Int = 1

b. tail

This will return all elements of a set except the first.

scala> s.tail
res1: scala.collection.immutable.Set[Int] = Set(4, 3)

c. isEmpty

If the set is empty, this will return a Boolean true; otherwise, false.

scala> s.isEmpty
res2: Boolean = false

Concatenating Scala Sets

There are two ways to concatenate sets. Let’s take another Scala set for this:

scala> var s1=Set(7,9,8,9)
s1: scala.collection.immutable.Set[Int] = Set(7, 9, 8)

a. The ++ Operator

scala> s++s1
res3: scala.collection.immutable.Set[Int] = Set(1, 9, 7, 3, 8, 4)
scala> s++s1
res4: scala.collection.immutable.Set[Int] = Set(1, 9, 7, 3, 8, 4)
scala> s1++s
res5: scala.collection.immutable.Set[Int] = Set(1, 9, 7, 3, 8, 4)

b. The Set.++() Method

We can call the ++() method to either set and pass the other to it.

scala> s.++(s1)
res6: scala.collection.immutable.Set[Int] = Set(1, 9, 7, 3, 8, 4)
scala> s1.++(s)
res7: scala.collection.immutable.Set[Int] = Set(1, 9, 7, 3, 8, 4)

Read: Scala Operators with Syntax and Examples

Max and Min in a Set

We can find the maximum and minimum values in a set.

a. max

This returns the maximum value from a set.

scala> s.max
res8: Int = 4

b. min

This returns the minimum value from a set.

scala> s.min
res9: Int = 1

Finding Values Common to Two Sets

To determine the values common to two certain sets, we can use one of two methods. Let’s take two new sets for this:

scala> var a=Set(1,4,3,4,2)
a: scala.collection.immutable.Set[Int] = Set(1, 4, 3, 2)
scala> var b=Set(7,9,8,2,8)
b: scala.collection.immutable.Set[Int] = Set(7, 9, 8, 2)

a. The Set.&() Method

We can call &() on one set, and pass another to it.

scala> a.&(b)
res10: scala.collection.immutable.Set[Int] = Set(2)

b. Set.intersect() Method

We can use the intersect() method.

scala> a.intersect(b)
res11: scala.collection.immutable.Set[Int] = Set(2)
scala> b.intersect(a)
res12: scala.collection.immutable.Set[Int] = Set(2)

Read: Scala Functions with Syntax and Examples

Methods to Call on a Set

Playing around with sets in Scala, you can call these methods on them. (Note that they do not modify the set itself)

a. def +(elem: A): Set[A]

This adds an element to the set and returns it. (But doesn’t modify the original set)

scala> a.+("6")
res15: String = Set(1, 4, 3, 2)6

b. def -(elem: A): Set[A]

This removes the element from the set and then returns it. Note that this takes an Int instead of a string for our set of Ints.

scala> a.-(2)
res19: scala.collection.immutable.Set[Int] = Set(1, 4, 3)
scala> a.-(6)
res21: scala.collection.immutable.Set[Int] = Set(1, 4, 3, 2)

c. def contains(elem: A): Boolean

If the set contains that element, this returns true; otherwise, false.

scala> a.contains(2)
res22: Boolean = true
scala> a.contains(6)
res23: Boolean = false

d. def &(that: Set[A]): Set[A]

This returns an intersection of two sets, as we just saw.

scala> a.&(b)
res24: scala.collection.immutable.Set[Int] = Set(2)

e. def &~(that: Set[A]): Set[A]

&~ stands for set difference.

scala> a.&~(b) #All elements that are in a, but not in b
res25: scala.collection.immutable.Set[Int] = Set(1, 4, 3)
scala> b.&~(a) #All elements that are in b, but not in a
res26: scala.collection.immutable.Set[Int] = Set(7, 9, 8)

f. def +(elem1: A, elem2: A, elems: A*): Set[A]

This adds multiple elements to a Scala set and returns it.

scala> a.+(0,6,7)
res27: scala.collection.immutable.Set[Int] = Set(0, 1, 6, 2, 7, 3, 4)

g. def ++(elems: A): Set[A]

This concatenates a set with another collection.

scala> a.++(List(7,9,8))
res29: scala.collection.immutable.Set[Int] = Set(1, 9, 2, 7, 3, 8, 4)
scala> a.++(b)
res30: scala.collection.immutable.Set[Int] = Set(1, 9, 2, 7, 3, 8, 4)

h. def -(elem1: A, elem2: A, elems: A*): Set[A]

This removes, each element mentioned from the set.

scala> a.-(2,3,6)
res31: scala.collection.immutable.Set[Int] = Set(1, 4)

i. def addString(b: StringBuilder): StringBuilder

This adds all elements of the set to the String Builder.

scala> a.addString(new StringBuilder())
res32: StringBuilder = 1432

j. def addString(b: StringBuilder, sep: String): StringBuilder

This uses a separator to the above functionality.

scala> a.addString(new StringBuilder(),"*")
res33: StringBuilder = 1*4*3*2

k. def apply(elem: A)

This checks whether the element is part of the set.

scala> a.apply(1)
res34: Boolean = true
scala> a.apply(7)
res35: Boolean = false

Read: Scala DataTypes

l. def count(p: (A) => Boolean): Int

This returns the count of elements that satisfy the predicate.

scala> a.count(x=>{x%2!=0})
res36: Int = 2

m. def copyToArray(xs: Array[A], start: Int, len: Int): Unit

These copies len elements from the set to the Array xs, starting at position start.

scala> var c=Array(0,0,0,0,0,0,0,0)
c: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0)
scala> a.copyToArray(c,3,2)
scala> c
res39: Array[Int] = Array(0, 0, 0, 1, 4, 0, 0, 0)

n. def diff(that: Set[A]): Set[A]

This returns the set difference(elements existing in one set, but not in another)

scala> a.diff(b)
res40: scala.collection.immutable.Set[Int] = Set(1, 4, 3)
scala> b.diff(a)
res42: scala.collection.immutable.Set[Int] = Set(7, 9, 8)

o. def drop(n: Int): Set[A]]

This returns all elements except the first n.

scala> a.drop(2)
res45: scala.collection.immutable.Set[Int] = Set(3, 2)

p. def dropRight(n: Int): Set[A]

This Scala set returns all elements except the last n.

scala> a.dropRight(2)
res46: scala.collection.immutable.Set[Int] = Set(1, 4)

q. def dropWhile(p: (A) => Boolean): Set[A]

This drops elements until the first element that doesn’t satisfy the predicate.

scala> a.dropWhile(x=>{x%2!=0})
res48: scala.collection.immutable.Set[Int] = Set(4, 3, 2)

r. def equals(that: Any): Boolean

This set in Scala compares the set to another sequence.

scala> a.equals(List(1,4,3,2))
res50: Boolean = false

s. def exists(p: (A) => Boolean): Boolean

If the predicate holds true for some elements in the set, this returns true; otherwise, false.

scala> a.exists(x=>{x%4==0})
res52: Boolean = true
scala> a.exists(x=>{x%5==0})
res53: Boolean = false

t. def filter(p: (A) => Boolean): Set[A]

This filters such elements (see the previous method)

scala> a.filter(x=>{x%4==0})
res54: scala.collection.immutable.Set[Int] = Set(4)

u. def find(p: (A) => Boolean): Option[A]

This Scala set returns the first element that satisfies the predicate.

scala> a.find(x=>{x%2==0})
res55: Option[Int] = Some(4)

v. def forall(p: (A) => Boolean): Boolean

This returns true if all elements of the set satisfy the predicate; otherwise, false.

scala> a.forall(x=>{x%2==0})
res56: Boolean = false

w. def head: A

This Scala Set returns the first element from the set.

scala> a.head
res59: Int = 1

x. def init: Set[A]

This returns all elements from the set, except the last.

scala> a.init
res62: scala.collection.immutable.Set[Int] = Set(1, 4, 3)

y. def intersect(that: Set[A]): Set[A]

This returns the intersection of two sets(elements common to both).

scala> a.intersect(b)
res64: scala.collection.immutable.Set[Int] = Set(2)
scala> b.intersect(a)
res65: scala.collection.immutable.Set[Int] = Set(2)

z. def isEmpty: Boolean

This set in Scala returns true if the set is empty; otherwise, false.

scala> a.isEmpty
res66: Boolean = false

Read: Scala String: Creating String, Concatenation, String Length

aa. def iterator: Iterator[A]

This creates a new iterator over the set.

scala> a.iterator
res67: Iterator[Int] = non-empty iterator

ab. def last: A

This returns the last element from a set.

scala> a.last
res68: Int = 2

ac. def map[B](f: (A) => B): immutable.Set[B]

This Scala Set applies the function to all elements of the set and returns it.

scala> a.map(x=>x*2)
res69: scala.collection.immutable.Set[Int] = Set(2, 8, 6, 4)

ad. def max: A

This returns the highest value from the set.

scala> a.max
res70: Int = 4

ae. def min: A

This returns the lowest element.

scala> a.min
res71: Int = 1

af. def mkString: String

This Scala set represents all elements of the set as a String.

scala> a.mkString
res72: String = 1432

ag. def mkString(sep: String): String

This lets us define a separator for the above method’s functionality.

scala> a.mkString("*")
res73: String = 1*4*3*2

ah. def product: A

This returns the algebraic product of all elements in the set.

scala> a.product
res74: Int = 24

ai. def size: Int

This returns the size of the set.

scala> a.size
res75: Int = 4

aj. def splitAt(n: Int): (Set[A], Set[A])

This splits the set at the given index and returns the two resulting subsets.

scala> a.splitAt(2)
res76: (scala.collection.immutable.Set[Int], scala.collection.immutable.Set[Int]) = (Set(1, 4),Set(3, 2))
scala> a.splitAt(3)
res77: (scala.collection.immutable.Set[Int], scala.collection.immutable.Set[Int]) = (Set(1, 4, 3),Set(2))

ak. def subsetOf(that: Set[A]): Boolean

If the set passed as argument is a subset of this set, this returns true; else, false.

scala> Set(3,2).subsetOf(a)
res79: Boolean = true
scala> Set(2,3).subsetOf(a)
res80: Boolean = true
scala> Set(1,3,4).subsetOf(a)
res82: Boolean = true

al. def sum: A

This returns the sum of all elements of the set.

scala> a.sum
res83: Int = 10

am. def tail: Set[A]

This returns all elements of the set except the first.

scala> a.tail
res84: scala.collection.immutable.Set[Int] = Set(4, 3, 2)

an. def take(n: Int): Set[A]

This Scala set returns the first n elements from the set.

scala> a.take(3)
res85: scala.collection.immutable.Set[Int] = Set(1, 4, 3)

ao. def takeRight(n: Int):Set[A]

This returns the last n elements.

scala> a.takeRight(3)
res86: scala.collection.immutable.Set[Int] = Set(4, 3, 2)

ap. def toArray: Array[A]

This returns an Array holding elements from the set.

scala> a.toArray
res87: Array[Int] = Array(1, 4, 3, 2)

aq. def toList: List[A]

This returns a List from elements of the set.

scala> a.toList
res88: List[Int] = List(1, 4, 3, 2)

ar. def toSeq: Seq[A]

This returns a sequence from the set.

scala> a.toSeq
res90: Seq[Int] = Vector(1, 4, 3, 2)

as. def toString(): String

This represents the elements of the set as a String.

scala> a.toString
res91: String = Set(1, 4, 3, 2)

This was all about Scala Sets.

Conclusion

This is all about how to declare and process Scala sets. Next, we will discuss Scala Maps. Furthermore, if you have any query, feel free to ask in the comment section.
For reference

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.

Leave a Reply

Your email address will not be published. Required fields are marked *