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
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.
- class Array<T> private constructor(){
- val size:Int
- operator fun get(index: Int):T
- operator fun set(index: Int, value :T): Unit
- operator fun iterator(): Iterator<T>
-
- }
You can create an array using any of the library functions.
Using arrayOf( )
- fun main(args:Array<String>)
- {
- var num= arrayOf("sun","mon","tue","wed","fri","sat","sun")
- for (i in num){
- print(" "+i)
- }
- }
-
Using intArrayOf
Integer type of array,
- fun main(args:Array<String>)
- {
- var num= intArrayOf(10,20,30,40,50)
- for (i in num){
- print(" "+i)
- }
- }
-
Using arrayOfNulls( )
- fun main(args:Array<String>)
- {
- var num= arrayOfNulls<String>(3)
- num.set(0,"Red")
- num.set(1,"Green")
- num.set(2,"Yellow")
- for (i in num)
- {
- println(i)
- }
- }
-
- Red
- Green
- Yellow
Iterable InterfaceThis interface enables collections to be represented as a sequence of elements and they can be iterate naturally.
For example,
- public interface Iterable<out T>{
- public abstract fun iterator():Iterable<T>
- }
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.
- package kotlin.collections
-
- public interface Iterable<out T> {
-
-
-
- public operator fun iterator(): Iterator<T>
- }
-
-
- public interface Collection<out E> : Iterable<E> {
- public val size: Int
-
- public fun isEmpty(): Boolean
- public operator fun contains(element: @UnsafeVariance E): Boolean
-
- override fun iterator(): Iterator<E>
- public fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
- }
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.
- fun main(args:Array<String>){
- var student:List<String> = listOf("Ram","Shyam","Akhil","Sameer")
- student.forEach {
- print(" "+it)
- }
- }
-
-
Note
This list contains the Mixed Type of data too.
- emptyList()
It creates an empty Immutable list. e. var emptylist:List<String> = emptyList<String>()
- listOfNotNull()
It creates an immutable list which can accept only not null elements.
- arrayListOf()
It creates a mutable list and return a java ArrayList.
- 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
- fun main(args:Array<String>){
- val mutableListNames: MutableList<String> = mutableListOf<String>("developer", "designer", "Project Manager")
- mutableListNames.add("Tester")
- mutableListNames.removeAt(1)
- mutableListNames[0] = "Coder"
- mutableListNames.forEach{
- print(" "+it)
- }
-
- val mutableListMixed = mutableListOf("BMW", "Toyota", 1, 6.76, 'v')
- println()
- mutableListMixed.forEach{
- print(" "+it)
- }
- }
- output: Coder Project Manager Tester
- 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.
- fun main(args:Array<String>){
-
- val mixedTypesSet = setOf(2, 4.454, "how", "far", 'c')
- mixedTypesSet.forEach {
- print(" "+it)
- }
- var intSet: Set<Int> = setOf(1, 3, 4)
- intSet.forEach {
- print(" "+it)
- }
- }
-
-
- 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
- fun main(args:Array<String>){
- val callingCodesMap: Map<Int, String> = mapOf(234 to "Nigeria", 1 to "USA", 233 to "Ghana")
- for ((key, value) in callingCodesMap) {
- println("$key is the calling code for $value")
- }
- print(callingCodesMap[234])
- }
-
-
-
-
-
-
-
-
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
- fun main(args:Array<String>){
- val personsHashMap: java.util.HashMap<Int, String>
- = hashMapOf(1 to "IT", 2 to "CSE", 3 to "EC")
- personsHashMap.put(4, "E")
- personsHashMap.forEach {
- print(" "+it)
- }
- personsHashMap.remove(2)
- println()
- print(personsHashMap[1])
- }
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.