Flavors of Collections

In Java, we’re used to different types of collections: List, Set, Map, and so on. We can use them in Kotlin as well. The mutable collection interfaces of Java are split into two interfaces in Kotlin: an immutable read-only interface and a mutable read-write interface. Kotlin also provides a number of convenience methods on collections in addition to those from the JDK.

Types of collections in Kotlin

When you’re ready to iterate over the elements in any of these collections, Kotlin makes that task easier and much more fluent than in Java. At a high level, you may use the following collections in Kotlin:

  • Pair—a tuple of two values.

  • Triple—a tuple of three values.

  • Array—indexed fixed-sized collection of objects and primitives.

  • List—ordered collection of objects.

  • Set—unordered collection of objects.

  • Map—associative dictionary or map of keys and values.

Since Java already offers a wide range of collections in the JDK, you may wonder what role Kotlin plays when working with collections. The improvement comes in two forms: through extension functions and views. Let’s discuss each of these separately.

Convenience methods added by Kotlin

Through the kotlin.collections package, of the standard library, Kotlin adds many useful convenience functions to various Java collections. You can use the Java collections from within Kotlin, in ways you’re familiar with. For the same collections, when coding in Kotlin, you can also use the methods that Kotlin has added.

For example, in Java, we may iterate over the elements of a List of String stored in a reference names using the traditional for-loop like so:

//Java code
for(int i = 0; i < names.size(); i++) { 

Alternatively, for greater fluency, we may use the for-each iterator:

//Java code
for(String name : names) { 

The latter is less noisy than the former, but we get only the elements and not the index in this case. This is also true if you use the functional style forEach in Java instead of the imperative style for-each iterator. Kotlin makes it convenient to get both the index and then value, by adding a withIndex() method. Here’s an example of using it:

Get hands-on with 1200+ tech skills courses.