Collections & Sequences
Kotlin's collection story: the read-only versus mutable interface split, the enormous set of extension operators over Iterable, lazy Sequences, ranges, and the small helper types around them. Data-shuffling code dominates real work, so this is heavily interviewed.
part ofKotlinoverview, primer and where to startread it →on this pageshowhide
explore
- How Kotlin Does Collections & Sequences5 questions
- Collection Types & Builders30 questions
- Read-Only vs Mutable Interfaces5 questions
- Factory Functions5 questions
- buildList / buildMap Builders5 questions
- Read-Only Views vs True Immutability5 questions
- Array & Primitive Array Types5 questions
- Map & Set Semantics5 questions
- Collection Operations32 questions
- Transformations6 questions
- Aggregation & Folding5 questions
- Grouping & Association5 questions
- Windowing, Chunking & Zipping6 questions
- Ordering & Comparators5 questions
- Element Access & Search5 questions
- Sequences & Lazy Pipelines25 questions
- Lazy Evaluation Model5 questions
- Intermediate vs Terminal Operations5 questions
- Sequence vs Collection Performance5 questions
- generateSequence5 questions
- sequence{} Builder & yield5 questions
- Ranges & Progressions15 questions
- Range Operators5 questions
- IntRange & Progressions5 questions
- Range Membership & Char Ranges5 questions
- Tuples, Iterators & Ordering Contracts15 questions
- Pair, Triple & Destructuring5 questions
- Iterable & Iterator Protocol5 questions
- Comparable & Comparator5 questions
questions
122 · 6 sectionsIn Kotlin, what is the difference between List and MutableList (and Set/MutableSet, Map/MutableMap), and how does the read-only/mutable split work?
basics
~10 sList lets you only read elements; MutableList also lets you add, remove, or change them. The same idea applies to Set/MutableSet and Map/MutableMap. You pick the type based on whether the data should change.
Kotlin's collection operators like map, filter, and groupBy aren't methods on the collection classes. Where do they come from, and what does that imply?
basics
~20 sThey are extension functions defined in the Kotlin standard library, not members of the collection classes. They work on any Iterable or Collection, so the same operators apply to lists, sets, and even Java collections.
Contrast an eager collection pipeline with a lazy Sequence pipeline in Kotlin. When does asSequence() actually pay off, and when does it not?
basics
~20 sA normal list pipeline processes the whole collection at each step, creating a new list every time. A Sequence processes one element through all steps before moving on, with no intermediate lists, and can stop early. Sequences help on big data or early exit.
Predict and explain the result types of these on a Set/Map: `setOf(3,1,2).map { it }`, `setOf(1,2,3).filter { it > 1 }`, and `mapOf(1 to "a").filter { it.key == 1 }`. Why do they differ?
basics
~20 smap on a Set gives a List. filter on a Set gives a List too. filter on a Map gives a Map. The result type depends on which operator and which receiver, because transforming can change duplicates and ordering.
You're designing a public Kotlin API. How do you use the read-only/mutable collection model to express intent and protect invariants, given that read-only types aren't truly immutable?
basics
~10 sAccept and return read-only types (List, Set, Map) so callers can't change your data, and copy incoming or outgoing collections when you need a real guarantee. Use mutable types only inside your implementation.
How do you create an array in Kotlin and read/write its elements?
basics
~10 sUse arrayOf(1, 2, 3) to make one, then read or change an element with square brackets like a[0] or a[0] = 9. Get the length with a.size.
What does the buildList { } function do, and what is the type of the value it returns?
basics
~10 sbuildList gives you a temporary mutable list to fill inside the braces, then hands back a normal read-only List. You add items with add(), and the final list cannot be changed afterward.
How do you create a collection in Kotlin using factory functions like listOf, setOf, and mapOf, and what do they return?
basics
~10 sUse listOf(1, 2, 3), setOf(...), or mapOf("a" to 1) to build collections quickly. They give you read-only collections you cannot add to or remove from.
What does map[key] return in Kotlin when the key is absent, and how is that different from map.getValue(key)?
basics
~10 smap[key] gives you null when the key isn't there, so the result type is nullable. map.getValue(key) instead throws an exception if the key is missing, returning a non-null value when it exists.
When you call mapOf(...) or setOf(...) in Kotlin, what concrete JVM type backs the result, and what does that mean for iteration order?
basics
~10 sKotlin's default maps and sets keep elements in the order you inserted them. They are backed by LinkedHashMap and LinkedHashSet, so looping over them gives you items in insertion order.
Given a list of numbers, how do you compute its sum, average, and count in Kotlin, and how do you sum a numeric property of a list of objects?
basics
~10 sUse sum() to add numbers, average() for the mean, count() for how many. To sum a field of objects, use sumOf { it.field }, which adds up the chosen value for each item.
In Kotlin, what is the difference between accessing a list element with `list[i]`, `list.getOrNull(i)`, and `list.getOrElse(i) { default }`? When does each fail or succeed?
basics
~10 slist[i] throws an error if the index is out of range. getOrNull(i) returns null instead of throwing. getOrElse(i) { ... } returns a value you compute when the index is out of range.
What does the standard-library function `groupBy` do, and what is the exact type of the value it returns?
basics
~10 sgroupBy sorts items into buckets using a key you choose. It returns a map where each key points to a list of all the items that produced that key.
How do you sort a List in Kotlin, and what is the difference between sorted(), sortedBy { }, and sortedDescending()?
basics
~20 sUse sorted() to order items from low to high. Use sortedBy { } to sort by a chosen property. Use sortedDescending() for high to low. All three return a new list and leave the original unchanged.
What do the standard library functions map and filter do on a Kotlin collection, and what does each return?
basics
~20 smap turns each element into something else and gives back a new list of the results. filter keeps only the elements that match a condition and gives back a new list. Both leave the original list unchanged.
What does generateSequence(seed) { next } do, and how do you stop it from producing values forever?
basics
~10 sIt makes a lazy stream that starts at the seed and repeatedly applies your function to get the next value. It stops when your function returns null. Until then, it never ends.
On a Kotlin Sequence, what is the difference between an intermediate operation and a terminal operation? Give examples of each.
basics
~10 sIntermediate operations like map and filter just describe work and return a new sequence without doing anything yet. Terminal operations like toList or sum actually run the pipeline and give you a final result.
What does the sequence{} builder do in Kotlin, and how do you emit elements from inside it?
basics
~10 ssequence{} creates a lazy sequence. Inside the block you call yield(x) to hand out one value at a time, only producing them as the consumer asks for them.
What does asSequence() do to a collection chain, and how does processing differ from calling map/filter directly on a List?
basics
~10 sasSequence() makes the chain lazy. Instead of building a new list after each map/filter, each element flows through every step one at a time, only when a result is finally needed.
What is the difference between a List and a Sequence in Kotlin, and when would you choose a Sequence for performance?
basics
~20 sA List runs each step fully and makes a new list every step. A Sequence is lazy: it pulls one element all the way through the chain. Use Sequences for long chains over large data.
What is an IntRange in Kotlin, and how does it relate to IntProgression? How do you iterate one in a for-loop?
basics
~20 sAn IntRange is a span of integers from a start to an end value, like 1 to 10. You can loop over it with a for-loop, and each step it gives you the next number.
In Kotlin, how do you check whether a value lies inside a range, and what does the `in` operator do under the hood for a range like `1..10`?
basics
~10 sUse the in keyword: x in 1..10 is true when x is between 1 and 10, both ends included. !in checks the opposite. It calls the range's contains method.
How do you create a range of integers in Kotlin, and what does the `..` operator produce?
basics
~10 sWrite 1..5 to make a range from 1 to 5 including both ends. You can then loop over it with for (i in 1..5).
How do `step` and `downTo` change the type and iteration of a range? What are first, last, and step after `10 downTo 1 step 3`?
basics
~10 sstep changes how far each jump is, and downTo counts backwards. Together they make a progression that goes down. For 10 downTo 1 step 3 you get 10, 7, 4, 1.
How do you build a descending range and how do you change the increment? Explain `downTo` and `step`.
basics
~10 sUse downTo to count down, like 5 downTo 1. Use step to skip values, like 0..10 step 2 for 0,2,4,6,8,10. You can combine them: 10 downTo 0 step 2.
What is the Comparable interface in Kotlin, and what does implementing compareTo give you?
basics
~10 sComparable means a type has a built-in natural order. You write compareTo, which returns a negative number, zero, or positive number. Then you can sort the items and use < and > on them.
What does Kotlin's `for (x in something)` loop actually require of `something`, and how does it relate to `Iterable` and `Iterator`?
basics
~10 sA for loop works on anything that has an iterator() function. That function returns an iterator with hasNext() and next(), which the loop calls repeatedly to walk through the elements.
How do you create a Pair in Kotlin, and what does the 'to' infix function do?
basics
~10 sA Pair holds two values. You make one with Pair(a, b) or, more commonly, with the 'to' word, like 1 to "one". 'to' just builds a Pair of its left and right values.
How do you build a multi-key Comparator in Kotlin using compareBy, thenBy, and thenByDescending? Show ascending-then-descending ordering.
basics
~10 sUse compareBy to pick the first sort key, then chain thenBy for the next key and thenByDescending to flip a key's direction. Pass the result to sortedWith to sort by several fields in order.
Explain how destructuring works for Pair and Triple, and what componentN functions are.
basics
~10 sYou can unpack a Pair into two variables in one line: val (k, v) = pair. Kotlin does this by calling component1() and component2() behind the scenes. Triple adds component3() for a third variable.