
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin Array - toSet() Function
The Kotlin array toSet() function is used to convert an array or collection into a set. This function return a set preserves the element iteration order of the original array.
The sets does not contains duplicate elements, any duplicate in the array will removed in the resulting set.
Syntax
Following is the syntax of Kotlin array toSet() function −
fun <T> Array<out T>.toSet(): Set<T>
Parameters
This function does not accepts any parameter.
Return value
This function returns a set containing all elements of an array in the same order.
Example 1
Following is a basic example to demonstrate the use of toSet() function to return a set −
fun main(args: Array<String>){ var arr = arrayOf(3, 4, 5, 6) print("Array: ") println(arr.joinToString()) // use toSet function to convert an array to set val arr_to_set = arr.toSet() println("set: "+ arr_to_set) }
Output
The above code generate following output −
Array: 3, 4, 5, 6 set: [3, 4, 5, 6]
Example 2
Let's see another example. Here, we use the toSet function to return a set containing elements of an array in same order −
fun main(args: Array<String>) { // array of integers val intArray = arrayOf(1, 2, 3, 4, 5) // Convert the array to a set val intSet: Set<Int> = intArray.toSet() // display the list println("Set: $intSet") }
Output
Following is the output −
Set: [1, 2, 3, 4, 5]
Example 3
Let's continue with the another example to convert an array to a set and demonstrate how duplicates are removed −
fun main(args: Array<String>) { // Define an array with some duplicate elements val array = arrayOf(1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6) // Convert the array to a set val set = array.toSet() // Display the original array and the resulting set println("Original array: ${array.joinToString(", ")}") println("Set: ${set.joinToString(", ")}") }
Output
The above code produce following output −
Original array: 1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6 Set: 1, 2, 3, 4, 5, 6, 7, 8