
- 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 Set - Size Property
The Kotlin Set size property is an attribute of the collection interface, used to return the number of elements available in the set.
We can access the size property directly without calling the function.
Syntax
Following is the syntax of Kotlin set size property −
Set.size
Parameters
size is a property so it does not accepts any parameters.
Return value
The size property returns the integer value that represents the length of the set.
Example 1: If Set is not Empty
Let's see a basic example of the size property, which returns number of elements in the set.
fun main(args: Array<String>) { val set = setOf(1, 2, 3, 4, 5) val totalElement = set.size println("Total number of elements: $totalElement") }
Output
Following is the output −
Total number of elements: 5
Example 2: Set with Duplicate Element
The following example gives the total number of elements in the current set and will only display distinct elements −
fun main(args: Array<String>) { val set = setOf(1, 2, 3, 4, 4, 1, 5) val totalElement = set.size println("Total number of elements: $totalElement") println("Distinct Element: " + set) }
Output
Following is the output −
Total number of elements: 5 Distinct Element: [1, 2, 3, 4, 5]
Example 3: If Set is Empty
This is another example of size property. If the set is empty, it returns 0 −
fun main(args: Array<String>) { val set = setOf<String>() val totalElement = set.size println("Total number of elements: $totalElement") println("Set's Element: " + set) }
Output
Following is the output −
Total number of elements: 0 Set's Element: []
kotlin_sets.htm
Advertisements