Practice with Collections

Created By: Geoffrey Challen
/ Updated: 2022-06-29

Let's pause before moving on to get more practice with Kotlin's collections—the lists, maps, and sets that are so useful for solving problems. We'll also learn how we can combine these collections together to build more interesting data structures. Let's get started!

Nested Collections

In the past lessons we've seen how to create and use several standard Kotlin collections: Lists, Maps, and Sets:

These collections are quite useful on their own! However, they can also be combined to great effect. Let's see an example.

Show how to use a mutableMapOf<String, MutableList<String>> to create a list of tasks for individual people. Demonstrate how to handle the case where the initial value is not present.

Lists of Maps of Sets

You can combine Lists, Maps, and Sets in many interesting ways to build data structures to solve problems. You can create Lists of Maps:

Or Sets of Lists:

But generally, it's more common for the top-level data structure to be a Map: Maps of Maps, Maps of Lists, and Maps of Sets. We'll get some practice working with these on this lesson's practice and homework problems.

Kotlin Maps and Nullability

One thing you may have noticed is that Kotlin's null checking doesn't work so well in some cases on maps. For example:

Let's briefly discuss why this is, and what we can do about it.

Discuss how null checking and Kotlin Maps collide, and make the case for the null assertion !! operator here.

Practice Problem Warm-Up

We'll spend the rest of the lesson working on some problems that test our understanding of how to nest collections. First, we're asked to parse a List<String> into a Map<Set<String>>. Let's do an example of that together, which you can use as a starting point for the practice problem that follows.

Set up the next homework problem and provide an example of how to insert a Set into a Map.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Homework Warm-Up

Next let's discuss how to approach this lesson's homework problem. This problem is a bit trickier, since we need to determine when to properly insert entries into our Map, and do some String parsing. So let's discuss how to get started.

Discuss the Script Parser homework problem, both how to parse the String, and how to only add to the Map when needed.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

More Practice

Need more practice? Head over to the practice page.