A Kotlin Set is a data collection tool that contains unique elements, though it cannot contain duplicate elements. Sets are used where we want to ensure that duplicate values are not stored and distinct values are stored. The data is stored in an unordered way in the set. In today’s tutorial, we will learn how to create a set and discuss different types of sets, mainly the differences between them.
Mastering Set in Kotlin: A Comprehensive Guide with Examples
First of all, the Set is divided into 2 Parts in Kotlin:
- Immutable Set: After creating an immutable set you cannot modify its elements like no adding or removing.
123val immutableSet = setOf("Apple", "Banana", "Cherry")// immutableSet.add("Date") // This will give a compile-time error - Mutable Set: In a mutable set you can perform add, edit, and delete operations on the set.
123456val mutableSet = mutableSetOf("Apple", "Banana")mutableSet.add("Cherry")println("Mutable Set: $mutableSet")// OutputMutable Set: [Apple, Banana, Cherry]
What If we add duplicate items in Set in Kotlin:
If we add duplicate items in Kotlin then it overrides the existing item and does not add again duplicate entry. See the mentioned example for more clarity.
1 2 3 4 5 6 7 8 9 10 |
val mutableSet = mutableSetOf("Apple", "Banana") mutableSet.add("Cherry") mutableSet.add("Cherry") mutableSet.add("Apple") mutableSet.add("Banana") println("Mutable Set: $mutableSet") // Output Mutable Set: [Apple, Banana, Cherry] |
Types of Set in Kotlin:
- HashSet: A hash set does not preserve its element insertion order. When you fetch inserted items again from the set, they may not be in the same order as they were inserted. However, it is very efficient for basic CURD operations (Add, Edit, and Delete).
1234567891011121314fun main() {val hashSet = hashSetOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)hashSet.add(6)hashSet.add(14)hashSet.remove(2)println("HashSet: $hashSet") // Output order is not guaranteedprintln("Contains 3: ${hashSet.contains(3)}")}// OutputHashSet: [1, 3, 4, 5, 6, 7, 8, 9, 10, 14]Contains 3: true - LinkedHashSet: A linked hash set is important when you want to preserve the insertion order of elements.
12345678910fun main() {val linkedHashSet = linkedSetOf("Apple", "Banana", "Cherry")linkedHashSet.add("Date")println("LinkedHashSet: $linkedHashSet") // Order is preserved}// OutputLinkedHashSet: [Apple, Banana, Cherry, Date] - TreeSet: A Tree Set automatically maintains its elements in sorted order. TreeSet in Kotlin is based on the Red-Black tree structure. It is used when you want to automatically sort the elements.
12345678910fun main() {val treeSet = sortedSetOf(5, 3, 8, 1, 2)treeSet.add(4)println("TreeSet (Sorted): $treeSet")}// OutputTreeSet (Sorted): [1, 2, 3, 4, 5, 8]
How to use Set with custom model class in Kotlin:
When we move to professional development in Kotlin then single data sets are not that useful. They are good for practice as a beginner because you learn the basics. But when moving to a large project we will always use custom model data classes. In a custom model class, we can define which type of data we want to store in a Set and make a Single data object. In our example, we are creating a class Person with 2 member variables name and age.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
data class Person(val name: String, val age: Int) fun main() { // Creating instances of the Person class val person1 = Person("Alice", 30) val person2 = Person("Bob", 25) val person3 = Person("Alice", 30) // Same properties as person1 val person4 = Person("Bob", 25) val person5 = Person("Bob", 25) // Using a Set to store unique persons val personSet = mutableSetOf(person1, person2, person3, person4, person5) // Printing the set println("Person Set: $personSet") } // Output Person Set: [Person(name=Alice, age=30), Person(name=Bob, age=25)] |
Basic Set Methods:
- add(): To add elements in Set.
1234567val mutableSet = mutableSetOf(1, 2, 3)mutableSet.add(4)println(mutableSet)// Output: [1, 2, 3, 4] - remove(): To remove an element from Set.
1234567val mutableSet = mutableSetOf(1, 2, 3, 4)mutableSet.remove(3)println(mutableSet)// Output: [1, 2, 4] - contains(): To check whether a Set contains a specific value or not.
12345678val set = setOf(1, 2, 3, 4)println(set.contains(3))// Output: trueprintln(set.contains(5))// Output: false - union(): Merge two sets into a single one.
123456789val set1 = setOf(1, 2, 3)val set2 = setOf(3, 4, 5)val unionSet = set1.union(set2)println(unionSet)// Output: [1, 2, 3, 4, 5] - intersect(): To get common elements between two sets.
12345678val set1 = setOf(1, 2, 3)val set2 = setOf(3, 4, 5)val intersectSet = set1.intersect(set2)println(intersectSet)// Output: [3] - isEmpty(): To check whether a Set is empty or not.
12345val set = emptySet<Int>()println(set.isEmpty())// Output: true - size(): Get the length of the set.
12345val set = setOf(1, 2, 3, 4)println(set.size)// Output: 4 - forEach(): To iterate or print each element of the set using a loop.
12345678val set = setOf("Apple", "Banana", "Cherry")set.forEach { println(it) }// Output:// Apple// Banana// Cherry
I have explained the most commonly used Set method in my tutorial, But there are a lot more available on Kotlin’s official documentation. I am mentioning the link HERE. If you have any queries regarding Kotlin please feel free to comment. Happy coding.