![]() |
VOOZH | about |
Kotlin provides a rich set of tools for working with collections like lists, sets, and maps. Whether you want to add, remove, sort, filter, or transform data, Kotlin’s standard library makes it easy and expressive.
Collection operations are declared in two ways:
These are built directly into the collection types. For example:
These are core operations that every collection type should support. If you’re building your own custom collection class, you’ll need to implement these yourself. To make that easier, Kotlin gives you helper classes like AbstractList, AbstractSet, and AbstractMap that provide basic behavior out of the box.
Most other helpful collection operations like filter(), map(),sorted(), etc. are implemented as extension functions. These let you add new behavior to existing classes without modifying them. These functions work for both mutable (can change) and read-only (cannot change) collections.
Kotlin offers a long list of powerful operations you can use on collections. Here are the main types of operations you’ll often use:
All the operations discussed above return their results without affecting the original content of the collection. For example, when we apply to filter operation then it produces a new collection that contains all the elements matching the filtering predicate. Results of these operations should be either stored in variables or could be passed to other functions.
Kotlin program using filter operation:
Output:
Original collection elements still unchanged [Geeks, for, Geeks, A, Computer, Portal]
New Collection obtains after filtering [Geeks, Geeks, Computer, Portal]
For limited collection operations, we can specify the destination object and it is optional. Destination should be mutable collection to which the function add its resulting items instead of returning them in a new object. To perform these operations with destinations, we can separate functions with the To postfix notation in their names, for example, use filterTo() instead of filter().
Kotlin program of using destination object:
Output:
Combined Result of both operations [Computer, Portal, Geeks]As we discussed above we can pass the collection operation result to another function and these functions return the destination collection back, so we can create it right in the corresponding argument of the function call:
Kotlin program of storing result in Hashset:
Output:
Only Distinct item length return by hashset [1, 3, 5, 6, 8]When you're using mutable collections (like MutableList, MutableSet, or MutableMap), you can directly change their contents. Kotlin gives you write operations for that like add(), remove(), clear(), and more. Some functions behave differently depending on whether you want to change the original or create a new result.
For example:
Kotlin program of using sort() and sorted() operation:
Output:
Original still unsorted: [3, 1, 4, 2]
New sorted list: [1, 2, 3, 4]
Original list after in-place sort: [1, 2, 3, 4]