Kotlin From Scratch: Ranges and Collections

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.

In the previous article in this series, you learned about nullability, loops, and conditions in Kotlin. In this tutorial, we’ll continue to learn the language by looking at the ranges and collections API in Kotlin.

1. Ranges

A Range in Kotlin is a unique type that defines a start value and an end value. In other words, it is an interval between a start and an end value. Ranges in Kotlin are closed, meaning that the start value and end value are included in the range.

We’ll now look at the different ways of creating ranges in Kotlin.

The .. Operator

In the code above, we have created a closed range. This variable oneToFive will include the following values: 1, 2, 3, 4, 5. We can loop over it using the for loop construct.

The code above can be shortened to:

We can also create a range of characters:

The variable aToZ will have all the letters in the English alphabet.

The rangeTo() Function

The .. operator can be replaced with the rangeTo() extension function to create a range. For example, we can also do this 1.rangeTo(5) and it would still have the same results as using the .. operator as discussed earlier.

The downTo() Function

This is another extension function that will create a range starting from a given number down to another one.

We can modify the range using the step() function. This will modify the delta between each element in the range.

The code above will contain odd numbers between 1 and 10.

The in Operator

The in operator is used to ascertain whether a value is present in a given range.

In the code above, we checked to see if 5 is in the range 1..10 using the in operator. We can also do the opposite by using !n to check if 5 is not in the range.

The until() and step() Function

The until() and step() functions are similar to the downTo() function we discussed above. You can use them to create a range of numbers with your specified step. These functions are implemented as infix functions and you will learn more about them in a  later tutorial about Kotlin functions.

All you have to remember at this point is that infix functions allow you to make a function call without using the dot or parenthesis notation. For example, this function call:

Is equivalent to this infix function call:

2. Collections

Collections are used to store groups of related objects in memory. We can retrieve, store or organize the objects in a collection. Kotlin provides its collections API as a standard library built on top of the Java Collections API. (We’ll discuss interfaces in Kotlin in a future post.)

You should note that these interfaces are linked to their implementation at compile time. You can’t see the implementation source code in Kotlin, because the collections are actually implemented by the standard Java Collections such as ArrayList, Maps, HashMap, Sets, HashSet, List and so on. To really understand the collections API in Kotlin, you’ll need to be familiar with these basic classes and interfaces in Java.

In this section, we’ll learn about the List, Set and Map collections in Kotlin. (If you want a refresher on arrays in Kotlin, kindly visit the first tutorial in this series.)

Kotlin’s collections give us the ability to achieve a lot with just a little code—unlike in Java, which seems to need a lot of code to achieve a little! Kotlin has two variants of collections: mutable and immutable. A mutable collection provides us with the ability to modify a collection by either adding, removing or replacing an element. Immutable collections cannot be modified and don’t have these helper methods.

Note that the addition, removal or replacement of an element in an immutable collection is possible via operator functions (we’ll get to that shortly), but these will end up creating a new collection.

The Iterable Interface

The Kotlin Iterable interface is at the top of the collections class hierarchy. This interface enables collections to be represented as a sequence of elements (which can be iterated over, naturally).

The Collection Interface

The Kotlin Collection interface extends the Iterable interface. The Collection interface is immutable. In other words, you have read-only access to collections. The Set and List interfaces (more about these shortly) in Kotlin extend this interface.

Some of the functions and properties available in the Collection interface are:

  • size: this property returns the size of the collection.
  • isEmpty(): returns true if the collection is empty or false otherwise.
  • contains(element: E): returns true if the element specified in the argument is present in the collection.
  • containsAll(element: Collection<E>): returns true if the element in the collection passed as argument is present in the collection.

The MutableIterable Interface

This interface in Kotlin gives us a specialized mutable iterator from the parent Iterable interface.

The MutableCollection Interface

The MutableCollection interface in Kotlin is a specialized interface that enables collections to be mutable. In other words, add and remove operations can be performed on a given collection. This interface extends both the Collection interface and the MutableIterable interface already discussed above. The MutableSet and MutableList interfaces (we’ll get to them shortly) in Kotlin extend this interface. The functions available in this interface—apart from the ones available in its parents—are:

  • add(element: E): adds the element passed as an argument to the collection and returns true if successful or false if the collection does not support duplicates and the element is already present.
  • remove(element: E): removes the element passed as an argument from the collection. Returns true if successful or false if it was not present in the collection.
  • addAll(elements: Collection<E>): adds all the elements in the collection passed as arguments to the collection. Returns true if successful or false if nothing was added.
  • removeAll(elements: Collection<E>): removes all of the elements present in the collection passed as arguments. Returns true if successful or false if nothing was removed.
  • retainAll(elements: Collection<E>): retains only the elements present in the collections passed as arguments. Returns true if successful or false if nothing was retained.
  • clear(): removes all elements from this collection.

Now you have learned about the top interfaces in the collection class hierarchy in Kotlin, let’s now look into how Kotlin handles collections such as Lists, Sets and Maps in the remaining part of the tutorial.

Lists

A list is an ordered collection of elements. This is a popular collection that is widely used. Let’s look at different ways of creating a list in Kotlin.

Using the listOf() Function

In Kotlin, we can create an immutable (read-only) list using the listOf() helper function from the Kotlin standard library. This function returns a Kotlin List interface type.

Running the code above will print:

Moreover, we can pass values of different types into the listOf() as arguments and the result will still work—it will be a list of mixed type.

Using the emptyList() Function

This function just creates an empty immutable list and returns a Kotlin List interface type.

Now, you might ask what purpose does that serve? The ability to create an empty list is helpful when you are writing a program where some other code further down the line requires you to have a list and be able to invoke its methods but you won’t have any elements to populate the list under certain conditions. For example, listing all the files in an empty directory.

Using the listOfNotNull() Function

This function creates a new immutable list containing only elements that are not null. Notice that this function also returns a Kotlin List interface type.

In the above code, the nonNullsList actually becomes [2, 45, 2, 5] because all the null elements are disregarded by the code. This is why we get the output 5 for accessing the element at index 3.

The List interface from the Kotlin standard library extends only the Collection interface. In other words, its only parent is the Collection interface. It overrides all the functions in the parent interface to cater for its special needs and also defines its own functions, such as:

  • get(index: Int): a function operator that returns the element at the specified index.
  • indexOf(element: E): returns the index of the first occurrence of the element passed as an argument in the list, or -1 if none is found.
  • lastIndexOf(element: E): returns the index of the last occurrence of the element passed as an argument in the list, or -1 if none is found.
  • listIterator(): returns a list iterator over the elements in the list.
  • subList(fromIndex: Int, toIndex: Int): returns a list that contains the portion of the list between the specified start and end indices.

Using the arrayListOf() Function

This creates a mutable list and returns a Java ArrayList type.

Since this is a mutable list, it supports different functions for the addition and removal of elements from the list. For instance, the add() function to insert an element at a specific index. You can also directly change the elements at a specific index.

Using the mutableListOf() Function

To add, remove or replace values in a list, we need to make the list a mutable one. We can convert an immutable list to a mutable one by calling the function toMutableList() on the list. However, note that this method will create a new list.

To create a mutable list of a certain type from scratch, e.g. String, we use mutableListOf<String>(), while for mixed types we can just use the mutableListOf() function instead.

Any of these functions will return a MutableList Kotlin interface type. This interface extends both the MutableCollection and List interfaces discussed earlier in this section. The MutableList interface adds methods for the retrieval or substitution of an item based upon its position:

  • set(index: Int, element: E): substitutes an element in the list with another element. This returns the element previously at the specified position.
  • add(index: Int, element: E): inserts an element at the specified index.
  • removeAt(index: Int): gets rid of the element at a particular index.

Running the code above, we produce the following result:

Note that all these functions create a Java ArrayList behind the scenes.

You might now ask how is using arrayListOf() different than using mutableListOf() if both these versions simply create an ArrayList under the hood. The primary difference between these two is that mutableListOf() is more appropriate when you are planning to write multi-platform code. The function mutableListOf() will always give something back that implements the MutableList interface without you having to worry about the implementation. So, it might currently create an ArrayList but that could change in future but you can be rest assured that it will always implement the MutableList interface. On the other hand, you will always get an ArrayList when using the arrayListOf() function.

Sets

A set is an unordered collection of unique elements. In other words, it can’t have any duplicates! Let’s look at some of the different ways of creating a set in Kotlin. Each of these creates a different data structure which is optimized for a certain kind of task.

Using the setOf() Function

To create an immutable (read-only) set in Kotlin, we can use the function setOf(), which returns a Kotlin Set interface type.

Note that the Kotlin Set interface extends only the Kotlin Collection interface and overrides all the properties available in its parent.

You cannot access the elements in a set directly by using the intSet[1] element index notation. However, the function elementAt() will do the job for you.

Using the hashSetOf() Function

Using the hashSetOf() function creates a Kotlin MutableSet interface backed by a HashMap instance which stores elements in a hash table. Because this function creates a Kotlin HashSet type, we can add, remove, or clear elements in the set. In other words, it’s mutable.

Using the sortedSetOf() Function

Using the sortedSetOf() function creates a Java TreeSet collection behind the scenes, which orders elements based on their natural ordering or by a comparator. This set is also mutable.

Using the linkedSetOf() Function

This function creates a LinkedHashSet. This mutable set maintains a linked list of the entries in the set, in the order in which they were inserted.

Using the mutableSetOf() Function

We can use mutableSetOf() to create a mutable set. This function returns a Kotlin MutableSet interface type. Behind the scenes, this function simply creates a Java LinkedHashSet.

The MutableSet interface extends both the MutableCollection and the Set interfaces.

Maps

Maps associate keys to values. The keys must be unique, but the associated values don’t need to be. That way, each key can be used to uniquely identify the associated value, since the map makes sure that you can’t have duplicate keys in the collection. Behind the scenes, Kotlin uses the Java Map collection to implement its map collection type.

Using the mapOf() Function

To create an immutable or read-only Map collection in Kotlin, we use the mapOf() function. We create a map with this function by giving it a list of pairs—the first value is the key, and the second is the value. Calling this function returns a Kotlin Map interface type.

Running the code above will produce the result:

Unlike the List and Set interfaces in Kotlin that extend the Collection interface, the Map interface doesn’t extend any at all. Some of the properties and functions available in this interface are:

  • size: this property returns the size of map collection.
  • keys: this property returns an immutable Set of all the keys in the map.
  • values: returns an immutable Collection of all the values in the map.
  • entries: returns a read-only set of all key-value pairs in the map.
  • isEmpty(): returns true if the map is empty or false otherwise.
  • containsKey(key: K): returns true if the map contains the key in the argument.
  • containsValue(value: V): returns true if the map maps one or more keys to the value passed as an argument.
  • get(key: K): returns the value matching the given key or ‘null’ if none is found.

Using the mutableMapOf() Function

The mutableMapOf() function creates a mutable map for us so that we can add and remove elements in the map. This returns a Kotlin MutableMap interface type.

The MutableMap interface doesn’t extend the MutableCollection interface. Its only parent is the Map interface. It overrides the keys, entries and values properties from the parent interface in order to redefine them. Here are some of the extra functions available in the MutableMap interface:

  • put(key: K, value: V): inserts the key, value pair into the map. This will return the previous value linked with the key or null if the key was not previously used.
  • remove(key: K): removes the key and its linked value from the map.
  • putAll(from: Map<out K, V>): updates the map with all the data from the given map. New keys will be added, and existing keys will be updated with new values.
  • clear(): removes all elements from the map.

We can get the value for a key using the get() function. We can also use square bracket notation as a shortcut for get().

Using the hashMapOf() Function

Using this function creates a HashMap type that is mutable. The HashMap class uses a hash table to implement the  MutableMap interface.

Using the linkedHashMap() Function

This function returns an implementation of MutableMap based on Hash table. It also maintains the iteration order of all its entries. This is done with the help of a doubly linked list of all the map entries.

Using the sortedMapOf() Function

This function creates a Java SortedMap type which is mutable. The Java SortedMap class sees that the entries in the map are maintained in an ascending key order.

Remember, implementation of these collection interfaces in Kotlin happens at compile time.

Collections Operation Functions

Kotlin provides us with many useful operator functions called extension functions that can be invoked on collections. Let’s take a look at some of the most useful.

The last() Function

This operator function returns the last element in a collection such as a list or set. We can also supply a predicate to search within a subset of elements.

The first() Function

This operator function returns the first element when invoked on a collection such as a list or set. If a predicate is given, it then uses the predicate to restrict the operation to a subset of elements.

The maxorNull() Function

Invoking this operator function on a collection such as a list or set returns the largest element, or null if there are no elements in the collection. This functionality was originally provided by max() but that is now deprecated.

The drop() Function

Calling this operator function returns a new list or set containing all elements except the first n elements.

The plus() Function

This operator function returns a collection containing all elements of the original and then the given element if it isn’t already in the collection. This will end up creating a new list instead of modifying the list.

The minus() Function

The opposite of the plus() function is the minus() function. It returns a collection containing all elements of the original set except the given element. This also ends up creating a new list instead of altering the list.

The average() Function

Calling this operator function will return an average of all the elements in the collection.

Most of these extension functions are available in the Kotlin collections standard library. You are advised to check out the documentation to learn about the others.

Conclusion

In this tutorial, you learned about the range and collections API in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you’ll be introduced to functions in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Chike Mgbemena

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.

In the previous article in this series, you learned about nullability, loops, and conditions in Kotlin. In this tutorial, we'll continue to learn the language by looking at the ranges and collections API in Kotlin.

1. Ranges

A Range in Kotlin is a unique type that defines a start value and an end value. In other words, it is an interval between a start and an end value. Ranges in Kotlin are closed, meaning that the start value and end value are included in the range.

We'll now look at the different ways of creating ranges in Kotlin.

The .. Operator

In the code above, we have created a closed range. This variable oneToFive will include the following values: 1, 2, 3, 4, 5. We can loop over it using the for loop construct.

The code above can be shortened to:

We can also create a range of characters:

The variable aToZ will have all the letters in the English alphabet.

The rangeTo() Function

The .. operator can be replaced with the rangeTo() extension function to create a range. For example, we can also do this 1.rangeTo(5) and it would still have the same results as using the .. operator as discussed earlier.

The downTo() Function

This is another extension function that will create a range starting from a given number down to another one.

We can modify the range using the step() function. This will modify the delta between each element in the range.

The code above will contain odd numbers between 1 and 10.

The in Operator

The in operator is used to ascertain whether a value is present in a given range.

In the code above, we checked to see if 5 is in the range 1..10 using the in operator. We can also do the opposite by using !n to check if 5 is not in the range.

The until() and step() Function

The until() and step() functions are similar to the downTo() function we discussed above. You can use them to create a range of numbers with your specified step. These functions are implemented as infix functions and you will learn more about them in a  later tutorial about Kotlin functions.

All you have to remember at this point is that infix functions allow you to make a function call without using the dot or parenthesis notation. For example, this function call:

Is equivalent to this infix function call:

2. Collections

Collections are used to store groups of related objects in memory. We can retrieve, store or organize the objects in a collection. Kotlin provides its collections API as a standard library built on top of the Java Collections API. (We'll discuss interfaces in Kotlin in a future post.)

You should note that these interfaces are linked to their implementation at compile time. You can't see the implementation source code in Kotlin, because the collections are actually implemented by the standard Java Collections such as ArrayList, Maps, HashMap, Sets, HashSet, List and so on. To really understand the collections API in Kotlin, you'll need to be familiar with these basic classes and interfaces in Java.

In this section, we'll learn about the List, Set and Map collections in Kotlin. (If you want a refresher on arrays in Kotlin, kindly visit the first tutorial in this series.)

Kotlin's collections give us the ability to achieve a lot with just a little code—unlike in Java, which seems to need a lot of code to achieve a little! Kotlin has two variants of collections: mutable and immutable. A mutable collection provides us with the ability to modify a collection by either adding, removing or replacing an element. Immutable collections cannot be modified and don't have these helper methods.

Note that the addition, removal or replacement of an element in an immutable collection is possible via operator functions (we'll get to that shortly), but these will end up creating a new collection.

The Iterable Interface

The Kotlin Iterable interface is at the top of the collections class hierarchy. This interface enables collections to be represented as a sequence of elements (which can be iterated over, naturally).

The Collection Interface

The Kotlin Collection interface extends the Iterable interface. The Collection interface is immutable. In other words, you have read-only access to collections. The Set and List interfaces (more about these shortly) in Kotlin extend this interface.

Some of the functions and properties available in the Collection interface are:

  • size: this property returns the size of the collection.
  • isEmpty(): returns true if the collection is empty or false otherwise.
  • contains(element: E): returns true if the element specified in the argument is present in the collection.
  • containsAll(element: Collection<E>): returns true if the element in the collection passed as argument is present in the collection.

The MutableIterable Interface

This interface in Kotlin gives us a specialized mutable iterator from the parent Iterable interface.

The MutableCollection Interface

The MutableCollection interface in Kotlin is a specialized interface that enables collections to be mutable. In other words, add and remove operations can be performed on a given collection. This interface extends both the Collection interface and the MutableIterable interface already discussed above. The MutableSet and MutableList interfaces (we'll get to them shortly) in Kotlin extend this interface. The functions available in this interface—apart from the ones available in its parents—are:

  • add(element: E): adds the element passed as an argument to the collection and returns true if successful or false if the collection does not support duplicates and the element is already present.
  • remove(element: E): removes the element passed as an argument from the collection. Returns true if successful or false if it was not present in the collection.
  • addAll(elements: Collection<E>): adds all the elements in the collection passed as arguments to the collection. Returns true if successful or false if nothing was added.
  • removeAll(elements: Collection<E>): removes all of the elements present in the collection passed as arguments. Returns true if successful or false if nothing was removed.
  • retainAll(elements: Collection<E>): retains only the elements present in the collections passed as arguments. Returns true if successful or false if nothing was retained.
  • clear(): removes all elements from this collection.

Now you have learned about the top interfaces in the collection class hierarchy in Kotlin, let's now look into how Kotlin handles collections such as Lists, Sets and Maps in the remaining part of the tutorial.

Lists

A list is an ordered collection of elements. This is a popular collection that is widely used. Let's look at different ways of creating a list in Kotlin.

Using the listOf() Function

In Kotlin, we can create an immutable (read-only) list using the listOf() helper function from the Kotlin standard library. This function returns a Kotlin List interface type.

Running the code above will print:

Moreover, we can pass values of different types into the listOf() as arguments and the result will still work—it will be a list of mixed type.

Using the emptyList() Function

This function just creates an empty immutable list and returns a Kotlin List interface type.

Now, you might ask what purpose does that serve? The ability to create an empty list is helpful when you are writing a program where some other code further down the line requires you to have a list and be able to invoke its methods but you won't have any elements to populate the list under certain conditions. For example, listing all the files in an empty directory.

Using the listOfNotNull() Function

This function creates a new immutable list containing only elements that are not null. Notice that this function also returns a Kotlin List interface type.

In the above code, the nonNullsList actually becomes [2, 45, 2, 5] because all the null elements are disregarded by the code. This is why we get the output 5 for accessing the element at index 3.

The List interface from the Kotlin standard library extends only the Collection interface. In other words, its only parent is the Collection interface. It overrides all the functions in the parent interface to cater for its special needs and also defines its own functions, such as:

  • get(index: Int): a function operator that returns the element at the specified index.
  • indexOf(element: E): returns the index of the first occurrence of the element passed as an argument in the list, or -1 if none is found.
  • lastIndexOf(element: E): returns the index of the last occurrence of the element passed as an argument in the list, or -1 if none is found.
  • listIterator(): returns a list iterator over the elements in the list.
  • subList(fromIndex: Int, toIndex: Int): returns a list that contains the portion of the list between the specified start and end indices.

Using the arrayListOf() Function

This creates a mutable list and returns a Java ArrayList type.

Since this is a mutable list, it supports different functions for the addition and removal of elements from the list. For instance, the add() function to insert an element at a specific index. You can also directly change the elements at a specific index.

Using the mutableListOf() Function

To add, remove or replace values in a list, we need to make the list a mutable one. We can convert an immutable list to a mutable one by calling the function toMutableList() on the list. However, note that this method will create a new list.

To create a mutable list of a certain type from scratch, e.g. String, we use mutableListOf<String>(), while for mixed types we can just use the mutableListOf() function instead.

Any of these functions will return a MutableList Kotlin interface type. This interface extends both the MutableCollection and List interfaces discussed earlier in this section. The MutableList interface adds methods for the retrieval or substitution of an item based upon its position:

  • set(index: Int, element: E): substitutes an element in the list with another element. This returns the element previously at the specified position.
  • add(index: Int, element: E): inserts an element at the specified index.
  • removeAt(index: Int): gets rid of the element at a particular index.

Running the code above, we produce the following result:

Note that all these functions create a Java ArrayList behind the scenes.

You might now ask how is using arrayListOf() different than using mutableListOf() if both these versions simply create an ArrayList under the hood. The primary difference between these two is that mutableListOf() is more appropriate when you are planning to write multi-platform code. The function mutableListOf() will always give something back that implements the MutableList interface without you having to worry about the implementation. So, it might currently create an ArrayList but that could change in future but you can be rest assured that it will always implement the MutableList interface. On the other hand, you will always get an ArrayList when using the arrayListOf() function.

Sets

A set is an unordered collection of unique elements. In other words, it can't have any duplicates! Let's look at some of the different ways of creating a set in Kotlin. Each of these creates a different data structure which is optimized for a certain kind of task.

Using the setOf() Function

To create an immutable (read-only) set in Kotlin, we can use the function setOf(), which returns a Kotlin Set interface type.

Note that the Kotlin Set interface extends only the Kotlin Collection interface and overrides all the properties available in its parent.

You cannot access the elements in a set directly by using the intSet[1] element index notation. However, the function elementAt() will do the job for you.

Using the hashSetOf() Function

Using the hashSetOf() function creates a Kotlin MutableSet interface backed by a HashMap instance which stores elements in a hash table. Because this function creates a Kotlin HashSet type, we can add, remove, or clear elements in the set. In other words, it's mutable.

Using the sortedSetOf() Function

Using the sortedSetOf() function creates a Java TreeSet collection behind the scenes, which orders elements based on their natural ordering or by a comparator. This set is also mutable.

Using the linkedSetOf() Function

This function creates a LinkedHashSet. This mutable set maintains a linked list of the entries in the set, in the order in which they were inserted.

Using the mutableSetOf() Function

We can use mutableSetOf() to create a mutable set. This function returns a Kotlin MutableSet interface type. Behind the scenes, this function simply creates a Java LinkedHashSet.

The MutableSet interface extends both the MutableCollection and the Set interfaces.

Maps

Maps associate keys to values. The keys must be unique, but the associated values don't need to be. That way, each key can be used to uniquely identify the associated value, since the map makes sure that you can't have duplicate keys in the collection. Behind the scenes, Kotlin uses the Java Map collection to implement its map collection type.

Using the mapOf() Function

To create an immutable or read-only Map collection in Kotlin, we use the mapOf() function. We create a map with this function by giving it a list of pairs—the first value is the key, and the second is the value. Calling this function returns a Kotlin Map interface type.

Running the code above will produce the result:

Unlike the List and Set interfaces in Kotlin that extend the Collection interface, the Map interface doesn't extend any at all. Some of the properties and functions available in this interface are:

  • size: this property returns the size of map collection.
  • keys: this property returns an immutable Set of all the keys in the map.
  • values: returns an immutable Collection of all the values in the map.
  • entries: returns a read-only set of all key-value pairs in the map.
  • isEmpty(): returns true if the map is empty or false otherwise.
  • containsKey(key: K): returns true if the map contains the key in the argument.
  • containsValue(value: V): returns true if the map maps one or more keys to the value passed as an argument.
  • get(key: K): returns the value matching the given key or 'null' if none is found.

Using the mutableMapOf() Function

The mutableMapOf() function creates a mutable map for us so that we can add and remove elements in the map. This returns a Kotlin MutableMap interface type.

The MutableMap interface doesn't extend the MutableCollection interface. Its only parent is the Map interface. It overrides the keys, entries and values properties from the parent interface in order to redefine them. Here are some of the extra functions available in the MutableMap interface:

  • put(key: K, value: V): inserts the key, value pair into the map. This will return the previous value linked with the key or null if the key was not previously used.
  • remove(key: K): removes the key and its linked value from the map.
  • putAll(from: Map<out K, V>): updates the map with all the data from the given map. New keys will be added, and existing keys will be updated with new values.
  • clear(): removes all elements from the map.

We can get the value for a key using the get() function. We can also use square bracket notation as a shortcut for get().

Using the hashMapOf() Function

Using this function creates a HashMap type that is mutable. The HashMap class uses a hash table to implement the  MutableMap interface.

Using the linkedHashMap() Function

This function returns an implementation of MutableMap based on Hash table. It also maintains the iteration order of all its entries. This is done with the help of a doubly linked list of all the map entries.

Using the sortedMapOf() Function

This function creates a Java SortedMap type which is mutable. The Java SortedMap class sees that the entries in the map are maintained in an ascending key order.

Remember, implementation of these collection interfaces in Kotlin happens at compile time.

Collections Operation Functions

Kotlin provides us with many useful operator functions called extension functions that can be invoked on collections. Let's take a look at some of the most useful.

The last() Function

This operator function returns the last element in a collection such as a list or set. We can also supply a predicate to search within a subset of elements.

The first() Function

This operator function returns the first element when invoked on a collection such as a list or set. If a predicate is given, it then uses the predicate to restrict the operation to a subset of elements.

The maxorNull() Function

Invoking this operator function on a collection such as a list or set returns the largest element, or null if there are no elements in the collection. This functionality was originally provided by max() but that is now deprecated.

The drop() Function

Calling this operator function returns a new list or set containing all elements except the first n elements.

The plus() Function

This operator function returns a collection containing all elements of the original and then the given element if it isn't already in the collection. This will end up creating a new list instead of modifying the list.

The minus() Function

The opposite of the plus() function is the minus() function. It returns a collection containing all elements of the original set except the given element. This also ends up creating a new list instead of altering the list.

The average() Function

Calling this operator function will return an average of all the elements in the collection.

Most of these extension functions are available in the Kotlin collections standard library. You are advised to check out the documentation to learn about the others.

Conclusion

In this tutorial, you learned about the range and collections API in the Kotlin programming language. In the next tutorial in the Kotlin From Scratch series, you'll be introduced to functions in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Android app development posts here on Envato Tuts!

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Chike Mgbemena


Print Share Comment Cite Upload Translate Updates
APA

Chike Mgbemena | Sciencx (2017-08-14T20:17:35+00:00) Kotlin From Scratch: Ranges and Collections. Retrieved from https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/

MLA
" » Kotlin From Scratch: Ranges and Collections." Chike Mgbemena | Sciencx - Monday August 14, 2017, https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/
HARVARD
Chike Mgbemena | Sciencx Monday August 14, 2017 » Kotlin From Scratch: Ranges and Collections., viewed ,<https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/>
VANCOUVER
Chike Mgbemena | Sciencx - » Kotlin From Scratch: Ranges and Collections. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/
CHICAGO
" » Kotlin From Scratch: Ranges and Collections." Chike Mgbemena | Sciencx - Accessed . https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/
IEEE
" » Kotlin From Scratch: Ranges and Collections." Chike Mgbemena | Sciencx [Online]. Available: https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/. [Accessed: ]
rf:citation
» Kotlin From Scratch: Ranges and Collections | Chike Mgbemena | Sciencx | https://www.scien.cx/2017/08/14/kotlin-from-scratch-ranges-and-collections/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.