Set in Kotlin
Set in Kotlin
Kotlin Set interface is a generic unordered collection of elements and it does not contain
duplicate elements. Kotlin supports two types of sets mutable and immutable.
setOf() is immutable means it supports only read-only functionalities and
mutableSetOf() is mutable means it supports read and write both functionality.
Sets are:
An unordered collection of elements.
Duplicate elements are not allowed in sets.
fun main()
{
//declaring a set of strings
val seta = setOf("Hello" , "to", "All")
//declaring a set of characters
val setb = setOf( "A" , "B" , "C" )
//declaring a set of integers
val setc = setOf( 1 ,2 , 3 , 4 )
Output:
HellotoAll
ABC
1234
fun main() {
Functions:
elementAt(index): Returns the element at the specified index in the set or
throws IndexOutOfBoundsException.
contains(element): Returns true if element exists in the set or returns false.
indexOf(element): Returns the index of the specified element in the set, or -1
if the specified element is not present in the set.
lastIndexOf(element): Returns the index of the last occurrence (or the only
occurrence) of the specified element in the set, or -1 if the specified element
is not present in the set.
first(): Returns first element in set or throws NoSuchElementException if set is
empty.
last(): Returns last element in set or throws NoSuchElementException if set is
empty.
isEmpty(): Returns true if set is empty else false.
count(): Returns the number of elements in this collection.
sum(): Returns the sum of all elements in this collection.
average(): Returns the average of all elements in this collection.
fun main() {
val languages = setOf<String>("Kotlin", "C++", "C", "Java", "Angular", "Kotlin")
val marks = setOf<Int>(95,96,94,90)
println("The size of set is: ${languages.size}")
println("Does Java exist in set: ${languages.contains("Java")}")
println("Does PHP exist in set: ${languages.contains("PHP")}")
println("Element at index 1: ${languages.elementAt(1)}")
println("The index of Kotlin is: ${languages.indexOf("Kotlin")}")
println("The index of PHP is: ${languages.indexOf("PHP")}")
println("The last index of Kotlin is: ${languages.lastIndexOf("Kotlin")}")
println("First element in set: ${languages.first()}")
println("Last element in set: ${languages.last()}")
println("Is set empty: ${languages.isEmpty()}")
// Mathematical functions
println("No. of elements in set: ${marks.count()}")
println("Sum of elements in set: ${marks.sum()}")
println("Average of elements in set: ${marks.average()}")
}
Output:
Both the methods are used to check whether an element is present in the set or
not?
var num = 5
println("The set contains the element $num or not?" +" "+captains.contains(num))
Output:
Output :
seta.isEmpty() is true
seta == setb is true
[]
fun main() {
val nums = mutableSetOf(3, 4, 5)
println(nums)
nums.add(6)
nums.add(7)
nums.addAll(setOf(8, 9, 10))
println(nums)
nums.remove(10)
println(nums)
nums.clear()
if (nums.isEmpty()) println("The set is empty")
else println("The set is not epty")
}
Output :
[3, 4, 5]
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
The set is empty
The example creates a mutable set and presents several its methods.
nums.add(6)
nums.add(7)
nums.addAll(setOf(8, 9, 10))
The add adds a new element at the end of the set. The addAll adds multiple
elements at the end of the set.
nums.clear()
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
[]
The set is empty
The union operation returns a set containing all distinct elements from both
collections.
fun main() {
println(nums3)
}
In the example, we have two sets of integers. We join the sets with the union
method.
[1, 2, 3, 4, 5]
fun main() {
We have a set of integers. With the map function, we multiply each set element by
2. The function returns a new list.
Reduction is a terminal operation that aggregates set values into a single value.
The reduce method applies a function against an accumulator and each element
(from left to right) to reduce it to a single value.
fun main() {
We calculate the sum of values. The total is the accumulator, the next is the next
value in the list.
45
Kotlin Set fold
fun main() {
We have a set of expenses. These expenses are applied on the initial amount of
cash available.
With the fold we deduce all the expenses from the cash and return the remaining
value.
370
This is the amount that we have after subtracting all the expenses on the available
amount of money.
Sometimes we need to work with more elements of a set when doing reductions.
We can use the chunked method to split the set into a list of lists.
fun main() {
println(res)
}
In the example, we have a set of six values. We want to achieve the following
operation: 1*2 + 3*4 + 5*6. For this, we need to split the list into chunks of two
values.
We split the set into a list of two-element lists and apply a fold on it. The next is a
list on which we can use the indexing operations.
44
The partition operation splits the original collection into pair of lists. The first list
contains elements for which the specified predicate yields true, while the second
list contains elements for which the predicate yields false.
fun main() {
println(nums2)
println(nums3)
}
We have a set of integers. With the partition method, we split the set into two
sublists; one contains negative, the other one positive values.
Using destructuring declaration, we split the set into two parts in one go.
The groupBy method groups elements of the original set by the key returned by the
given selector function, applied to each element. It returns a map where each
group key is associated with a list of corresponding elements.
fun main() {
These lines create a map, which has two keys: "even" and "odd". The "even"
points to a list of even values and the "odd" to a list of odd values.
Here we create a map with integer keys. Each key groups words that have a
certain length.
The any method returns true if at least one element matches the given predicate
function.
fun main() {
Here we check if the set contains at least one negative value. The method returns
a Boolean value.
The all returns true if all elements satisfy the given predicate function.
fun main() {
With the drop operations, we exclude some elements from the set.
fun main() {
With the dropWhile method, we exclude the first n elements that satisfy the given
predicate function.
With the dropLastWhile method, we exclude the last n elements that satisfy the
given predicate function.
The take operations are complementary to the drop operations. The take methods
form a new list by picking some of the set elements.
fun main() {
The take method creates a new list having the first three elements of the original
set.
The takeWhile takes the first n elements that satisfy the predicate function.
The takeIf methods takes all elements of the set if the condition in the predicate
function is met.
[4, 5, 3]
[-12, -8, -1]
[4, 5, 3, 2, 1]
[9, 7, 6, 5, 4, 3, 2, 1]
[4, 5, 3, 2, 1, -1, 7, 6, -8, 9, -12]