Using Collection In Kotlin

Introduction

Collections are used to store a group of related Objects in memory. Like Java, Kotlin also supports collection frameworks, however, it has a list of library methods to perform the operations. In this article, I am going to discuss all the concerns related to a collection with examples.

Collection Hierarchy

Collection Hierarchy

Array

An array is a variable which can store multiple values on different-different indexes. Kotlin has an Array class which has set and get functions, size property, and some other useful methods.

  1. class Array<T> private constructor(){  
  2.    val size:Int  
  3.    operator fun get(index: Int):T  
  4.    operator fun set(index: Int, value :T): Unit  
  5.    operator fun iterator(): Iterator<T>  
  6. //..  
  7. }   
You can create an array using any of the library functions.

Using arrayOf( )

  1. fun main(args:Array<String>)  
  2. {  
  3.  var num= arrayOf("sun","mon","tue","wed","fri","sat","sun")  
  4.     for (i in num){  
  5.         print(" "+i)  
  6.     }  
  7. }  
  8. //output : sun mon tue wed fri sat sun                                                

Using intArrayOf

Integer type of array,

  1. fun main(args:Array<String>)  
  2. {  
  3.     var num= intArrayOf(10,20,30,40,50)  
  4.     for (i in num){  
  5.         print(" "+i)  
  6.     }  
  7. }  
  8. //output: 10 20 30 40 50  

Using arrayOfNulls( )

  1. fun main(args:Array<String>)  
  2. {  
  3.     var num= arrayOfNulls<String>(3)  
  4.     num.set(0,"Red")  
  5.     num.set(1,"Green")  
  6.     num.set(2,"Yellow")  
  7.     for (i in num)  
  8.     {  
  9.         println(i)  
  10.     }  
  11. }  
  12. //output:  
  13. Red  
  14. Green  
  15. Yellow  
Iterable Interface

This interface enables collections to be represented as a sequence of elements and they can be iterate naturally.

For example,

  1. public interface Iterable<out  T>{  
  2.     public abstract fun iterator():Iterable<T>  
  3. }  

Collection Interface

This interface extends Iterable interface. It has the elements in read-only (immutable) mode. Collection interface is further extended by two more interfaces ‘Set’ and ‘List’. The methods of collection interfaces are shown below.

  1. package kotlin.collections  
  2.   
  3. public interface Iterable<out T> {  
  4.     /** 
  5.      * Returns an iterator over the elements of this object. 
  6.      */  
  7.     public operator fun iterator(): Iterator<T>  
  8. }  
  9.   
  10.   
  11. public interface Collection<out E> : Iterable<E> {  
  12.     public val size: Int  
  13.   
  14.     public fun isEmpty(): Boolean  
  15.     public operator fun contains(element: @UnsafeVariance E): Boolean  
  16.   
  17.     override fun iterator(): Iterator<E>  
  18.     public fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean  
  19. }  

List

It provides a list of functions in immutable (read only format). Some of them are,

listOf()

It is a helper function from Kotlin Standard Library. This function returns a Kotlin list interface.

  1. fun main(args:Array<String>){  
  2.     var student:List<String> = listOf("Ram","Shyam","Akhil","Sameer")  
  3.     student.forEach {  
  4.         print(" "+it)  
  5.     }  
  6. }  
  7.   
  8. // output: Ram Shyam Akhil Sameer  

Note

This list contains the Mixed Type of data too.

  1. emptyList()
    It creates an empty Immutable list. e. var emptylist:List<String> = emptyList<String>()

  2. listOfNotNull()
    It creates an immutable list which can accept only not null elements.

  3. arrayListOf()
    It creates a mutable list and return a java ArrayList.

  4. mutableListOf()
    This method is similar to arrayListOf() the only difference is that mutableListOf() contains some functions for purpose of add,remove and replace .We can use toMutableList() to convert immutable list to mutable list .

Example

  1. fun main(args:Array<String>){  
  2. val mutableListNames: MutableList<String> = mutableListOf<String>("developer""designer""Project Manager")  
  3. mutableListNames.add("Tester")  
  4. mutableListNames.removeAt(1)  
  5. mutableListNames[0] = "Coder" // replaces the element in index 0 with "Oluchi"  
  6. mutableListNames.forEach{  
  7.     print(" "+it)  
  8. }  
  9. // a mutable list of mixed types  
  10. val mutableListMixed = mutableListOf("BMW""Toyota", 1, 6.76, 'v')  
  11.     println()  
  12.     mutableListMixed.forEach{  
  13.         print(" "+it)  
  14.     }  
  15. }  
  16. output: Coder Project Manager Tester  
  17.  BMW Toyota 1 6.76 v  

Set

Set is a collection of unordered collection of unique elements. A set cannot have duplicate element. The important methods of set are below,

setof()

it returns a Kotlin interface of read-only type.

  1. fun main(args:Array<String>){  
  2.     // creates a immutable set of mixed types  
  3.     val mixedTypesSet = setOf(2, 4.454, "how""far"'c'// will compile  
  4. mixedTypesSet.forEach {  
  5.     print(" "+it)  
  6. }  
  7.     var intSet: Set<Int> = setOf(1, 3, 4)  // only integers types allowed  
  8.     intSet.forEach {  
  9.         print(" "+it)  
  10.     }  
  11. }  
  12.   
  13. //output: 2 4.454 how far c 1 3 4  
  • hashSetOf( )
    it stores element in hash table .It is mutable hence we can add,remove ,remove elements.

  • sortedSetOf( )
    It creates a Tree Set to store data. It is also mutable type.

  • linkedSetOf( )
    It returns a java LinkedHashSet type .It is also mutable.

Map

It provides the facility to store data in key and value formate.Library functions are following –

mapOf( )

It is used for the purpose of creating immutable collections in Kotlin.

Example

  1.  fun main(args:Array<String>){  
  2.     val callingCodesMap: Map<Int, String> = mapOf(234 to "Nigeria", 1 to "USA", 233 to "Ghana")  
  3.     for ((key, value) in callingCodesMap) {  
  4.         println("$key is the calling code for $value")  
  5.     }  
  6.     print(callingCodesMap[234]) // Nigeria  
  7. }  
  8.   
  9. /* 
  10. Output: 
  11. 234 is the calling code for Nigeria 
  12. 1 is the calling code for USA 
  13. 233 is the calling code for Ghana 
  14. Nigeria 
  15. */   

mutableMapOf( )

This is Map with mutable functionality .User can add or remove data in it.

hashMapOf( )

This map returns a Java HashMap type which is a mutable type.

Example

  1. fun main(args:Array<String>){  
  2.     val personsHashMap: java.util.HashMap<Int, String>  
  3.  = hashMapOf(1 to "IT", 2 to "CSE", 3 to "EC")  
  4.     personsHashMap.put(4, "E")  
  5.     personsHashMap.forEach {  
  6.     print(" "+it)  
  7.     }  
  8.     personsHashMap.remove(2)  
  9.     println()  
  10.     print(personsHashMap[1]) // will print IT  
  11. }   

linkedHashMap()

It returns java ‘LinkedHashMap’ type which is mutable.

sortedMapOf( )

This function returns ‘SortedMap’ mutable type class of java .It can be implemented like above example.

Conclusion

In this article, you have learned about interfaces, classes and library methods which are available in Kotlin and you can use them to store objects in memory. Kindly go through my previous articles to understand other concepts of Kotlin.


Similar Articles