A set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest element is at the head of the list. It maintains insertion order. Listset is used only for a small number of elements. We can create empty ListSet either by calling the constructor or by applying the function ListSet.empty. It's iterate and traversal methods visit elements in the same order in which they were first inserted.
Syntax:
var ListSetName = ListSet(element1, element2, element3, ....)
Operations with ListSet
Initialize a ListSet : Below is the example to create or initialize ListSet.
Scala
// Scala program to Initialize a ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
println("Initializing an immutable ListSet ")
// Creating ListSet
val listSet1: ListSet[String] = ListSet("GeeksForGeeks",
"Article", "Scala")
println(s"Elements of listSet1 = $listSet1")
}
}
Output:
Initializing an immutable ListSet
Elements of listSet1 = ListSet(Scala, Article, GeeksForGeeks)
Check specific elements in ListSet :
Scala
// Scala program to Check specific elements in ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
println("Initializing an immutable ListSet ")
// Creating ListSet
val listSet1: ListSet[String] = ListSet("GeeksForGeeks",
"Article", "Scala")
println(s"Elements of listSet1 = $listSet1")
println("Check elements of immutable ListSet")
// Checking element in a ListSet
println(s"GeeksForGeeks = ${listSet1("GeeksForGeeks")}")
println(s"Student = ${listSet1("Student")}")
println(s"Scala = ${listSet1("Scala")}")
}
}
Output:
Initializing an immutable ListSet
Elements of listSet1 = ListSet(Scala, Article, GeeksForGeeks)
Check elements of immutable ListSet
GeeksForGeeks = true
Student = false
Scala = true
Adding an elements in ListSet : We can add an element in ListSet by using + operator. below is the example of adding an element in ListSet.
Scala
// Scala program to Add an element in a ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
println("Initializing an immutable ListSet ")
// Creating ListSet
val listSet1: ListSet[String] = ListSet("GeeksForGeeks",
"Article", "Scala")
println(s"Elements of listSet1 = $listSet1")
// Adding element in ListSet
println("Add element of immutable ListSet ")
val listSet2: ListSet[String] = listSet1 + "Java"
println(s"Adding element java to ListSet $listSet2")
}
}
Output:
Initializing an immutable ListSet
Elements of listSet1 = ListSet(Scala, Article, GeeksForGeeks)
Add element of immutable ListSet
Adding element java to ListSet ListSet(Java, Scala, Article, GeeksForGeeks)
Adding two ListSet : We can add two ListSet by using ++ operator. below is the example of adding two ListSet.
Scala
// Scala program to Add two ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
println("Initializing an immutable ListSet ")
// Creating ListSet
val listSet1: ListSet[String] = ListSet("GeeksForGeeks",
"Article", "Scala")
println(s"Elements of listSet1 = $listSet1")
// Adding two ListSet
val listSet2: ListSet[String] = listSet1 ++ ListSet("Java",
"Csharp")
println(s"After adding two lists $listSet2")
}
}
Output:
Initializing an immutable ListSet
Elements of listSet1 = ListSet(Scala, Article, GeeksForGeeks)
After adding two lists ListSet(Java, Csharp, Scala, Article, GeeksForGeeks)
Remove element from the ListSet : We can remove an element in ListSet by using – operator. below is the example of removing an element in ListSet.
Scala
// Scala program to Remove element from the ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
println("Initializing an immutable ListSet ")
// Creating ListSet
val listSet1: ListSet[String] = ListSet("GeeksForGeeks",
"Article", "Scala")
println(s"Elements of listSet1 = $listSet1")
println("Remove element from the ListSet ")
val listSet2: ListSet[String] = listSet1 - ("Article")
println(s"After removing element from listset = $listSet2")
}
}
Output:
Initializing an immutable ListSet
Elements of listSet1 = ListSet(Scala, Article, GeeksForGeeks)
Remove element from the ListSet
After removing element from listset = ListSet(Scala, GeeksForGeeks)
Initialize an empty ListSet :
Scala
// Scala program to print empty ListSet
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
// Creating an empty ListSet
println("Initialize an empty ListSet")
val emptyListSet: ListSet[String] = ListSet.empty[String]
println(s"String type empty ListSet = $emptyListSet")
}
}
Output:
Initialize an empty ListSet
String type empty ListSet = ListSet()
Note: We can create empty ListSet either by applying the function ListSet.empty or by calling the constructor .
ListSet in Scala is an immutable collection that represents a set of elements as an ordered list. ListSet provides constant time operations for adding and removing elements, and it preserves the order of elements in the list.
Here are some key features and usage examples of ListSet:
- ListSet is immutable, meaning that its contents cannot be modified after creation.
- ListSet provides efficient constant time operations for adding and removing elements, as well as set operations such as union, intersection, and difference.
- ListSet preserves the order of elements in the list, making it useful for scenarios where the order of elements is important.
- ListSet can be used in a variety of scenarios, including removing duplicates from a list, checking for membership of elements in a set, and performing set operations on two or more sets.
Here's an example code snippet that demonstrates the usage of ListSet in Scala:
Scala
import scala.collection.immutable.ListSet
object ListSetExample {
def main(args: Array[String]): Unit = {
val listSet = ListSet(1, 2, 3, 3, 4, 5, 5)
// Add an element to the set
val updatedSet = listSet + 6
// Remove an element from the set
val removedSet = updatedSet - 4
// Check if an element is in the set
val containsElement = removedSet.contains(2)
// Get the union of two sets
val otherSet = ListSet(3, 4, 5, 6, 7)
val unionSet = removedSet.union(otherSet)
// Print the sets
println("Original set: " + listSet)
println("Updated set: " + updatedSet)
println("Removed set: " + removedSet)
println("Contains element: " + containsElement)
println("Union set: " + unionSet)
}
}
OutputOriginal set: ListSet(5, 4, 3, 2, 1)
Updated set: ListSet(6, 5, 4, 3, 2, 1)
Removed set: ListSet(6, 5, 3, 2, 1)
Contains element: true
Union set: ListSet(4, 7, 6, 5, 3, 2, 1)
In this example, we create a new ListSet and add, remove, and check for membership of elements in it. We also get the union of the ListSet with another ListSet. As we can see from the output, the ListSet preserves the order of elements in the list, and the set operations return new sets without modifying the original sets.
Similar Reads
Overview
Basics
Control Statements
Scala | Decision Making (if, if-else, Nested if-else, if-else if)Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Scala uses control statements to control the flow of execution of the prog
5 min read
Scala | Loops(while, do..while, for, nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the progr
5 min read
Break statement in ScalaIn Scala, we use a break statement to break the execution of the loop in the program. Scala programming language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop
3 min read
Scala | LiteralsAny constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean
4 min read
OOP Concepts
Methods
Strings
Scala Packages
Scala Trait
Collections
Scala ListsA list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
Scala ListBufferA list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u
6 min read
ListSet in ScalaA set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
6 min read
Scala MapMap is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m
5 min read
Scala | ArraysArray is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Scala | ArrayBufferArray in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf
4 min read
Scala | TupleTuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
Set in Scala | Set-1A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
3 min read
Set in Scala | Set-2Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
7 min read
BitSet in ScalaA set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s
5 min read
HashSet In ScalaHashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
4 min read
Stack in ScalaA stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v
3 min read
HashMap in ScalaHashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value
3 min read
TreeSet in ScalaSet is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax
4 min read
Iterators in ScalaAn iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
Scala | OptionThe Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta
3 min read