EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala Set

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala Set

Scala Set

Introduction to Scala Set

Set is a part of the collection and it is used to store elements. Just like Java it also does not contain duplicate elements in it. In scala there are two types of sets are available i.e. immutable and mutable.  Scala by default provides us immutable sets. But we can make our set mutable just by importing some packages. Set is used for strong and retrieving of data and it contains only unique elements if we try to add a duplicate element, it will discard those objects from it.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

var variableName : Set[DataType] = Set()

In the above syntax, we can just provide the data type and name of our set. Let’s take a practice syntax for better understanding;

var set1 : Set[String] = Set()

In this case, we are defining an empty set here with no value initialized but we can also initialize our set at the time of declaring itself see below;

var set1 = Set("val1", "val2", "val3", "and so on ...")

In this case we are assigning value to set at the time of the creation of set only. So we can create a set in two ways which are explained above.

How Does Set Work in Scala?

Scala sets are also used to store objects and to retrieve them. It uses == to check the duplicate elements in it as it contains the only unique element. In scala sets are iterable class and part of the collection. Let’s have a look for its subclass and structure;

Scala set to contain some supertype which are mentioned below;

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,543 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)
Equals SetOps Iterable IterableFactoryDefaults IterableOps
IterableOnceOps Set IterableOnce AnyRef Any

It also contains some Subclasses which are mentioned below;

ValueSet AbstarcteSet KeySet BitSet SortedSet
KeySortedSet HashSet Node ListSet Set1
Set2 Set3 Set4 Set TreeSet
LinkedKeySet ImmutableKeySortedSet BitSet1 BitSet2 BitsetN

Now we can a look for scala set hierarchy;

Set includes the following:

  • Iterable
  • Equals
  • SetOps
  • IterableFactory
  • IterableOnceExtensionMethods
  • AbstarctSet
  • ImmutableSet
  • MutableSet

Types of Members

Set has two types of members in it:

  • Abstract members
  • Concrete members

some important points that we should keep in mind while working with sets in scala:

1) Scala provides us immutable seta by default, but we can also create mutable sets by importing Scala.collection.mutable._ package.

2) In scala, we can create empty sets as well as we can also initialize them at the time of creation only.

3) It provides us various methods to work with it like List in scala some of the methods are: contains(), size(), bitset(), remove, etc.

4) Set only contains unique elements.

Examples to Implement Scala Set

Below are the examples:

Example #1 – for()

In this example, we are printing the values of different types of sets.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val set1: Set[Int] = Set(100, 200, 00, 400, 600, 900)
val set2 = Set("hello", "this is ", "string set", "bye")
// print set1
println("values in set1 are :: "+ set1)
// print set2
println("values in set2 are :: " )
for(setval<-set2)
{
println("value is ::" + setval)
}
}

Output:

Scala Set Example 1

Example #2 – contains()

This method checks elements in the set. Return true and false based on results.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val set1: Set[Int] = Set(100, 200, 00, 400, 600, 900)
val set2 = Set("hello", "this is ", "string set", "bye")
// print set1
println("values in set1 are :: "+ set1)
// print set2
println("values in set2 are :: " )
var result = set1.contains(400)
println("result for set is :: "+ result)
}

Output:

Scala Set Example 2

Example #3 – + ()

This method always returns a new set with all the previous element present in it.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val butset1 :BitSet = BitSet(100, 200, 00, 400, 600, 900)
println("elemets inside bit set are ::")
// bitSet+() to add more elemets
val bs1: BitSet = butset1 + 500 + 700
//bit set output
println("result for bitset is :: "+ bs1)
}

Output:

Scala Set Example 3

Example #4 – & ()

This method returns a new set that contains all the elements which are present in both of the sets.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val bit1: BitSet = BitSet(1, 4, 7 , 9, 10 , 3)
val bit2: BitSet = BitSet(3, 15, 20 , 40, 7 , 1)
// Applying BitSet&() function
val result: BitSet = bit1 & (bit2)
// Bit Set & output
println("result after & method is ::: " + result)
}

Output:

Scala Set Example 4

Example #5 – &~ ()

This method returns a new set that contains all the elements that are not present in both sets.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val bit1: BitSet = BitSet(1, 4, 7 , 9, 10 , 3)
val bit2: BitSet = BitSet(3, 15, 20 , 40, 7 , 1)
// Applying BitSet&() function
val result: BitSet = bit1 &~ (bit2)
// Bit Set &~ output
println("result after &~ method is ::: " + result)
}

Output:

Scala Set Example 5

Example #6 – – ()

This method will return a new set but does not contain the elements specify with this operator.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val bit1: BitSet = BitSet(1, 4, 7 , 9, 10 , 3)
val bit2: BitSet = BitSet(3, 15, 20 , 40, 7 , 1)
println("before :: "+ bit1)
// Applying BitSet&() function
val result: BitSet = bit1 - 10
// Bit Set - output
println("result after-~ method is ::: " + result)
}

Output:

BitSet Example 6

Example #7 – ++ ()

This method returns a new set that contains all the elements from both sets but not repeated once.

Code:

import scala.collection.immutable._
object Main extends App{
// Your code here!
val bit1: BitSet = BitSet(1, 4, 7 , 9, 10 , 3)
val bit2: BitSet = BitSet(3, 15, 20 , 40, 7 , 1)
println("before :: "+ bit1)
// Applying BitSet&() function
val result: BitSet = bit1 ++ bit2
// Bit Set ++ output
println("result after ++ method is ::: " + result)
}

Output:

Scala Set Example 7

Conclusion

Sets are used for storing and retrieving of our data. In scala, we have two types of sets that are immutable and mutable. If you want to store unique elements and want to remove the duplicity, then we should go for sets in scala.

Recommended Articles

This is a guide to Scala Set. Here we discuss a brief overview of Scala Set and its different examples along with code Implementation. You can also go through our other suggested articles to learn more –

  1. Kotlin vs Scala | Top 10 C0mparison
  2. Overview of Scala Data Types
  3. Scala for Loop | Top 6 Examples
  4. Scala High Order Functions

Scala Programming Training (3 Courses)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

1 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses) Learn More