Left Index

Kotlin setOf()

Kotlin sets tutorial shows how to work with sets in Kotlin. A set is a generic unordered collection of elements which allows no duplicates. Kotlin distinguishes between Immutable(read-only) and mutable(can be modify) sets. Read-only sets are created with setOf() and mutable set with mutableSetOf().

Example:
package com.theitbulls.kotlinex

import java.util.ArrayList
import java.util.HashMap

fun main(args: Array<String>) {
	var setEx = setOf<String>("Jony", "Tony", "John", "Hary")
	setEx.forEach { item -> println("Value: ${item}") }
}
Output:
Value: Jony
Value: Tony
Value: John
Value: Hary

How to iterate setOf() and sort?
package com.theitbulls.kotlinex

import java.util.ArrayList
import java.util.HashMap

fun main(args: Array<String>) {
	var setEx = setOf<String>("Jony", "Tony", "John", "Hary")
	// getting element using index
	println("Value at(2): ${setEx.elementAt(2)}")
	println()
	
	// get first element of set
	println("First element: ${setEx.first()}")
	// get last element of set
	println("Last element: ${setEx.last()}")
	println()

	// iterate using forEach loop	
	setEx.forEach { item -> println("Value: ${item}") }
	println()
	
	// iterate using iterator
	var iterate = setEx.iterator()
	while(iterate.hasNext()) {
		print("${iterate.next()}, ")
	}
	println("\n")
	
	// iterate using forEachIndexed()
	setEx.forEachIndexed({ index, item -> println("Value at(${index}): ${item}") })
	println()
	
	// iterate using index
	for(index in setEx.indices) {
		println("Value at(${index}): ${setEx.elementAt(index)}")
	}
	println()
	
	// sort setEx in ascending order
	var sorted = setEx.sorted()
	sorted.forEach { item -> print("${item}, ") }
	println("\n")
	
	// sort setEx in descending order
	var descSorted = setEx.sortedDescending()
	descSorted.forEach { item -> print("${item}, ") }
	println("\n")
}
Output:
Value at(2): John

First element: Jony
Last element: Hary

Value: Jony
Value: Tony
Value: John
Value: Hary

Jony, Tony, John, Hary, 

Value at(0): Jony
Value at(1): Tony
Value at(2): John
Value at(3): Hary

Value at(0): Jony
Value at(1): Tony
Value at(2): John
Value at(3): Hary

Hary, John, Jony, Tony, 

Tony, Jony, John, Hary, 


Some basic methods
package com.theitbulls.kotlinex

import java.util.ArrayList
import java.util.HashMap

fun main(args: Array<String>) {
	var setEx = setOf<Int>(34, 35, 11, 766, 92, 1, 30, 42)
	// total size of set
	println("Size: ${setEx.size}\n")
	
	// total size of set
	println("Count: ${setEx.count()}\n")
	
	// find maximum number in given set
	println("Maximum number: ${setEx.max()}\n")
	
	// find minimum number in given set
	println("Minimum number: ${setEx.min()}\n")
	
	// get sum of all set element
	println("Sum: ${setEx.sum()}\n")
	
	// get average of all set element
	println("Average: ${setEx.average()}\n")
}
Output:
Size: 8

Count: 8

Maximum number: 766

Minimum number: 1

Sum: 1011

Average: 126.375