Sets
Sets
are versatile collections designed to store a unique selection of elements. They are valuable tools when there is a need to work with a group of values without duplicates. Unlike lists, which allow repeated elements and maintain order, sets prioritize uniqueness and do not guarantee a specific order for their elements.
A set can be used with a wide range of data types and can be implemented for storing and managing elements in various scenarios. Kotlin’s Set
type is versatile, accommodating diverse data types like Int
, String
, Double
, Boolean
, and custom classes. A set is useful for managing data groups, and preventing duplicates.
Types of Sets
Kotlin offers two main types of sets, mutable sets and immutable.
1. Mutable Set
A mutable set is a dynamic collection that allows the programmer to add, remove, or modify its elements after creation. It is implemented using the mutableSetOf()
function.
The following code example demonstrates creating an empty mutable set, creating a mutable set with predefined values, performing add and remove operations on the mutable set, and finally, printing the updated set values:
fun main() {// Creating an empty mutable setval emptySet: MutableSet<Int> = mutableSetOf()// Creating a mutable set with initial valuesval mutableFruits: MutableSet<String> = mutableSetOf("apple", "banana", "orange")// Modifying a mutable setmutableFruits.add("grape") // Adds an element to the setmutableFruits.remove("banana") // Removes an element from the set// Printing the updated mutable setprintln("Fruit Set: $mutableFruits")}
Parameters of mutableSetOf()
:
The mutableSetOf()
function takes zero or more initial elements as its parameters. A comma-separated list of elements can be used to initialize a mutable set. If no elements are provided, an empty mutable set is created.
Note: The
mutableSetOf()
function will only contain unique elements. If you attempt to add the same item multiple times, only one copy will be stored.
2. Immutable Set
An immutable set is a static collection whose elements cannot be modified once the set is created. It is implemented using the setOf()
function.
The following code snippet shows how to create an empty immutable set and an immutable set with predefined number values:
fun main() {// Creating an empty immutable setval emptySet: Set<Int> = setOf()// Creating an immutable set with numbersval numbers: Set<Int> = setOf(1, 2, 3, 4, 5)}
Parameters of setOf()
:
The setOf()
function, similar to mutableSetOf()
, takes zero or more initial elements as its parameters.
It initializes the immutable set with the provided elements. If no elements are provided, an empty immutable set is created.
The following code demonstrates how to create sets, add and remove elements, check for element existence, iterate over elements, retrieve the set size, and convert sets to lists and arrays. The iteration process is also correctly executed:
Example
import java.util.*fun main() {// Creating a mutable setval mutableFruits = mutableSetOf("apple", "banana", "orange")// Adding Elements to the Mutable SetmutableFruits.add("grape")mutableFruits.add("apple")// Removing Elements from the Mutable SetmutableFruits.remove("banana")// Checking Element Existenceval containsApple = mutableFruits.contains("apple")println("Mutable Set Contains 'apple': $containsApple")// Iterating Over Elements in the Mutable Setprintln("Mutable Set Elements:")for (fruit in mutableFruits) {println(fruit)}// Set Sizeval mutableSize = mutableFruits.sizeprintln("Mutable Set Size: $mutableSize")// Converting Mutable Set to Listval mutableToList = mutableFruits.toList()println("Mutable Set converted to list: $mutableToList")// Creating an immutable setval immutableFruits = setOf("apple", "banana", "orange")// Checking Element Existence in the Immutable Setval containsOrange = immutableFruits.contains("orange")println("Immutable Set Contains 'orange': $containsOrange")// Iterating Over Elements in the Immutable Setprintln("Immutable Set Elements:")for (fruit in immutableFruits) {println(fruit)}// Set Sizeval immutableSize = immutableFruits.sizeprintln("Immutable Set Size: $immutableSize")// Converting Immutable Set to Listval immutableToList = immutableFruits.toList()println("Immutable Set converted to list: $immutableToList")// Converting Immutable Set to Arrayval immutableToArray = immutableFruits.toTypedArray()println("Immutable Set converted to array: ${immutableToArray.contentToString()}")}
The output for the above code will be:
Mutable Set Contains 'apple': trueMutable Set Elements:applegrapeorangeMutable Set Size: 3Mutable Set converted to list: [apple, grape, orange]Immutable Set Contains 'orange': trueImmutable Set Elements:applebananaorangeImmutable Set Size: 3Immutable Set converted to list: [apple, banana, orange]Immutable Set converted to array: [apple, banana, orange]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.