KotlinCS 124 LogoJava

Practice with Collections

var petNames = mutableMapOf<String, MutableList<String>>()
petNames["Geoffrey"] = mutableListOf()
petNames["Geoffrey"]!! += "Gracie"
petNames["Geoffrey"]!! += "Xyz"

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
Nested Collections

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

var friends = mutableListOf<String>("you")
friends += "Gracie"
var favoriteIceCreams = mutableMapOf<String, String>("me" to "Peanut Butter Fudge")
favoriteIceCreams["Gracie"] = "Human food yummy"
favoriteIceCreams["Xyz"] = "Yick"

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

// Task list example

Lists of Maps of Sets
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:

var values = mutableListOf<MutableMap<String, String>>()
var entry = mutableMapOf<String, String>()
entry["test"] = "me"
values += entry

Or Sets of Lists:

var first = mutableListOf("test", "me")
var second = mutableListOf<String>()
second += "test"
second += "me"
var set = mutableSetOf<List<String>>()
set += first
set += second
// Because first and second have the same items, adding second does not modify the set

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
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:

var map = mutableMapOf("test" to 1)
// This should work, but fails
map["test"] += 1

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

var map = mutableMapOf("test" to 1)
// This should work, but fails
map["test"] += 1

Lists to Map Warm-Up
Lists to Map 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.

// Warm-up for Section Lists to Map
Created By: CS 124 Staff
/ Version: 2022.2.0

Write a method called sectionListsToMap that, given a List of Strings, parses it into a Map<String, MutableSet<String>> as follows. Each String in the passed list contains a comma-separated list of names of people in a discussion section. The first name is the section leader, and the rest are students. Your map should map each section leader to the set of students in their section. No section leader or student will appear twice in the data set.

For example, given the Strings "challen,student1", "ruisong4,student2, student3" and "friendly,student4, student5", your map would have keys "challen", "ruisong4", and "friendly". "challen" would map to a set containing "student1", "ruisong4" would map to a set containing "student2" and "student3", and so on.

A few hints for approaching this problem. First, consider how to use .split and .trim appropriately to parse the input String. You should get this part to work before proceeding. Then consider when you need to create the map and each set, and how to populate them.

You should not need import statements to solve this problem. Rather, create your maps and sets using mutableMapOf() and mutableSetOf() where appropriate.

Homework Problem Warm-Up
Homework Problem Warm-Up

Today’s homework problem is a challenge! Your goal is to complete the implementation of the Hawaiian Word translator you began earlier this semester. Since this problem is more difficult than other homework problems, we’re giving you an extra day to complete it. And, at the end of the day, please remember that this is just one problem, and you have homework drops.

We’ll also get you started with a walkthrough to help you think about how to approach this problem.

Note that the problem asks you to throw an exception in certain cases, something that we have not yet covered. The walkthrough describes how to do that.

// Warm-up for Hawaiian Words

Homework: Hawaiian Words

Created By: CS 124 Staff
/ Version: 2022.7.0

Words from languages that we are unfamiliar with can be difficult to pronounce correctly. Phonetic pronunciation guides can help make them more accessible to us. For this problem, you will write a program that produces phonetic pronunciations for Hawaiian words.

Write a method getPronunciation that accepts a single non-null String containing a potential Hawaiian word and returns a String containing the pronunciation guide. If the passed is invalid, throw an IllegalArgumentException.

Hawaiian Characters

There are 12 valid characters in the Hawaiian language: a, e, i, o, u, p, k, h, l, m, n, and w. Each Hawaiian word passed into our program must be inspected to ensure it contains only these characters, because if it does not, then we don’t have a valid Hawaiian word. If the passed word is not valid, throw an IllegalArgumentException. Note that you do not need to handle spaces or any other characters. You should ignore case when examining the input String, but your pronunciation guide output String should be all lowercase.

The consonants in the Hawaiian language are pronounced similarly to the English versions. The only exception is 'w', which is pronounced as a "v" if it follows an 'i' or 'e' and pronounced as "w" otherwise.

The vowels in the Hawaiian language are a, e, i, o, and u:

  • 'a' sounds like "ah" like "aha"
  • 'e' sounds like "eh" like "egg"
  • 'i' sounds like "ee" like "bee"
  • 'o' sounds like "oh" like "obey"
  • 'u' sounds like "oo" like "mood"

Vowel groups are also present in the Hawaiian language. More complex words can have many vowels that when grouped together require additional rules. This means we can't simply replace all 'a's with "ah", and so on.

We will consider the following simplification of the Hawaiian vowel groups for this problem:

  • "ai" and "ae" sound like "eye"
  • "ao" and "au" sound like "ow"
  • "ei" sounds like "ay"
  • "eu" sounds like "eh-oo"
  • "iu" sounds like "ew"
  • "oi" sounds like "oy"
  • "ou" sounds like "ow"
  • "ui" sounds like "ooey"


Here are a few examples used by the test suite:

  • aloha: ah-loh-hah
  • keikikane: kay-kee-kah-neh
  • iwa: ee-vah
  • MaHALO: mah-hah-loh

Note that the testing process will start by testing "w", then move on to single vowels, then test vowel groups, and then proceed to more complicated inputs, some of which will be invalid. So you can design your solution incrementally following the progression of the test suites.


A few hints to help you get started.

One way to proceed is to examine each character in the input String and build up the pronunciation guide from an empty String as you go. However, for this to work, some rules need access to the previous character (like 'w') and others to the next character (vowel groups), so it may be helpful to record the current character as well as the previous and next characters inside your loop. Doing this safely requires some care, given that the previous and next character are not always valid depending on where you are in the String.

Usually you'll want to consume one character at a time. But when you find a vowel group, you'll need to make sure you skip the next character. For example, given the input "ai", you'll need to make sure you output only "eye" and not "eye-ee" or "ah-ee".

Finally, take care to insert dashes in the correct places. A pronunciation should never end in a dash. You can avoid this by keeping track of where you are inside the loop, but it may be simpler to simply detect if your pronunciation ends with a dash and remove it before returning.

CS People: Dina Katabi
CS People: Dina Katabi

Very few people can make a legitimate claim to the label “genius”. Dina Katabi is one of them. A full professor at MIT, her groundbreaking work on wireless networking and other topics has also earned her a MacArthur Fellowship, the substantial financial award unofficially known as the “Genius Grant”.

In this video she discusses some of her work, including the ability to use wireless signals is a way that you may find quite surprising:

More Practice

Need more practice? Head over to the practice page.