Collections in Kotlin

In this article, we will discuss about collections in kotlin. In this we will learn how to define list, set, map, hash, map etc. in Kotlin?
Submitted by Aman Gautam, on January 14, 2018

As we know that collections are used to store multiple relatedobjects under one name in the memory. They allow us to manage, organize and work upon the group of objects. Let us now discuss them one by one.

1) Arrays

As I have my previous article on arrays in kotlin, you can check that for details.

Example:

fun main(args: Array<String>) {
    var pet = arrayOfNulls<String>(3);
    pet[0] = "Dog"
    pet[1] = "Cat"
    // we can also use set method
    pet.set(2,"Rabbit")
    for(p in pet) 
        println(p)
}

Output

Dog
Cat
Rabbit

2) List

Unlike java, list in kotlin differs in mutable or immutable type collections. By default, all lists we create are immutable means we cannot add or remove any element once a list is created.

Example

fun main(args: Array<String>) {
	var pets = listOf<String>("dog","cat","rabbit")
	pets.add("gerbils")  //will produce an error
}

To create a mutable list,

var pets= mutableListOf<String>("dog","cat","rabbit")

we can modify the mutable list as,

pets[0] ="ferrets"    // update new value at index 0
pets.remove("cat");  // remove first occurrence of cat
pets.add("gerbils")  // add new pet gerbils
pets.removeAt(1);    // remove element at index

we can also create a list of mixed objects,

    var mixList= listOf("dog",123,1.22,'a')

Other List typesin kotlin are

  1. emptyList()
  2. listOfNotNull()
  3. arrayListOf()

3) Set

Unlike list, set is collection of onlyunique elements.

var set = mutableSetOf("dog","cat","rabbit")
set.add("ferrets")
set.remove("cat")

Here are few points to remember about sets,

  1. We cannot update existing element
  2. Cannot access any element by its index
  3. Any duplicate element doesn’t count. Here is an example,
var set= mutableSetOf("dog","cat","rabbit","cat")
println(set.size)

Output

3

We have another set types in kotlin

  1. hashSetOf()
  2. sortedSetOf()
  3. linkedSetOf()

4) Map

It is used to store data in key, value pair format. In a map, one key cannot map to more than one value.

We can use either Pair(key,value) or “key to value” in map declaration. Both result the same.

var square=mapOf(Pair(2,4),3 to 9 ,4 to 16)  
print( square.entries)   //[2=4, 3=9, 4=16]
println(square.get(3))   // 9

Printing map using for loop

	for((n,s) in square)
	println("number = $n square = $s")

Output

number = 2 square = 4
number = 3 square = 9
number = 4 square = 16

Some other map types are

  1. mutableMapOf()
  2. hashMapOf()
  3. sortedMapOf()



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.