Kotlin Collections: List / Set / Map — простими словами 🤙🏻 (основи програмування)

Alexander Khyzhun
4 min readSep 3, 2022

Привіт, arrays та collections майже сусіда, минулого разу ми розібрались з тим, що таке arrays, тому сьогодні прийшов час розібратись з collections. Дуже важливо і цікава тема, рекомендую на ній зробити зупинку, щоб краще зрозуміти що це таке і для чого воно потрібне, оскільки з цим ви будете працювати щодня!

Весь матеріал ви можете знайти переглянувши відео, але стислий конспект я залишу і тут.

Kotlin: Collections List/Set/Map

Basic information

Collection<T> є коренем в ієрархії колекцій. Цей інтерфейс пропонує звичайну поведінку незмінних колекцій: операції типу size, get і т. д.

Collection<T> успадковується від інтерфейсу Iterable<T>, який визначає операції для ітерації елементів. Collection можна використовувати як параметр функції, яка може працювати з різними типами колекцій. Для більш конкретних випадків слід використовувати спадкоємців Collection: List та Set.

Подібно до колекцій Java, Kotlin також представив концепцію колекцій. Колекція зазвичай містить кілька об’єктів одного типу, і ці об’єкти в колекції називаються елементами. Стандартна бібліотека Kotlin надає багатий набір інструментів для керування колекціями.

Types of Collections

In Kotlin collections are categorised into two forms.

  1. Immutable Collection
  2. Mutable Collection

Immutable Collection

It means that it supports only read-only functionalities and can not be modified its elements. Immutable Collections and their corresponding methods are:

  • List — listOf() and listOf<T>()
  • Set — setOf()
  • Map — mapOf()

List — It is an ordered collection in which we can access elements or items by using indices — integer numbers that define the position of each component. Elements can be repeated in a list any number of times. We can not perform add or remove operations in the immutable list.

val colors = listOf<String>(“Yellow”, “Green”, “Red”, “Red”, “Red”)
// [Yellow, Green, Red, Red, Red]

Set — It is a collection of unordered elements and does not support duplicate elements. It is a collection of unique elements. Generally, the order of set elements does not have a significant effect. We can not perform add or remove operations because it is an immutable

val colors = setOf<String>(“Yellow”, “Green”, “Red”, “Red”, “Red”)
// [Yellow, Green, Red]

Map — Map keys are unique and hold only one value for each key, it is a set of key-value pairs. Each key maps to exactly one value. The values can be duplicates but keys should be unique. Maps are used to store logical connections between two objects, for example, a student ID and their name. As it is immutable its size is fixed and its methods support read-only access.

val clothes = mapOf<String, String>(
“shoes” to “black”,
“pants” to “brown”,
“jackat” to “white”
)
// [{shoes=black}, {pants=brown}, {jackat=white}]

Mutable Collection

It supports both read and write functionalities. Mutable collections and their corresponding methods are:

  • List — mutableListOf()
  • Set — mutableSetOf()
  • Map — mutableMapOf()

MutableList — Since a mutable list supports read and writes operations, declared elements in the list can either be removed or added

val colors = mutableListOf<String>(
“Yellow”, “Green”, “Red”, “Red”, “Red”
)
// [Yellow, Green, Red, Red, Red]
colors.
add(“Black”)
// [Yellow, Green, Red, Red, Red, “Black”]
colors.
add(0, “White”)
// [White, Yellow, Green, Red, Red, Red, Black]

MutableSet — The mutable Set supports both read and write functionality. We can access add or remove elements from the collections easily and it will preserve the order of the elements.

val colors = mutableSetOf<String>(
“Yellow”, “Green”, “Red”, “Red”, “Red”
)
// [Yellow, Green, Red]
colors.
add(“Red”)
// [Yellow, Green, Red]
colors.
add(“Brown”)
// [Yellow, Green, Red, Brown]
colors.
remove(“Green”)
// [Yellow, Red, Brown]
colors.
remove(0)
// [Red, Brown]

MutableMap — It is mutable so it supports functionalities like put, removes, clear, etc

val clothes = mapOf<String, String>(
“shoes” to “black”,
“pants” to “brown”,
“jackat” to “blue”
)
// [{shoes=black}, {pants=brown}, {jackat=white}]
clothes.
put(“glasses”, “yellow”)
// [{shoes=black}, {pants=brown}, {jackat=white}, {glasses=blue}]

Additional Information About Java Collections

Before understanding the different components in the above framework, let’s first understand a class and an interface.

  • Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
  • Interface: Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, nobody). Interfaces specify what a class must do and not how. It is the blueprint of the class.

🎬 Ось мій канал, де будуть всі відео на різні теми в програмуванні:

📚 Ось мій Patreon, де будуть всі матеріали в текстовому форматі, додаткова інфа, розбір приклдів, домашні завдання, ІТ-словник, і тд:

Окрім цього, там є різні пропозиції, наприклад, можемо займатись 1х1, можу допомогти зробити резюме, проведу співбесіду і так далі.

🎬 Весь контент, який я роблю — це все мій особистий досвід.
Я пишу/знімаю все сам і ділюсь з вами корисною інформацією, яку ніхто не розповідає, тому підтримайте підпискою ❤️

🙂 На цьому у мене — все!
👉🏻 Ставте лексуси, підписуйтесь і будьте умнічками.

Якщо я правий — похваліть, якщо ні — посваріть.
Но в любому випадку не забудьте дати фідбек 😉

Успіхів! 🇺🇦🦄

ios, android, it, programming, software, engineer, инженер, базы данных, database, code, backend, frontend, webdevelopment, scrum, jira, HR, recruiter, coding, flutter, react, html, css, angular, kotlin, java, python, php, c++, c#, swift, reactnative, mobile, vlog, tutorials, how to, git, QA, BA, алгоритмы, скрам, джира, айти, робота, іт, програмування, алгоритми, розробка, інженерія, фронтенд, бекенд, андроїд, дизайн, кодити, кодінг, флатер, котлін, джава, уроки, навчання, менеджмент
image for preview

--

--

Alexander Khyzhun

🧙🏻‍♂️ Software Wizard 🎬 Tech blogger 🎌 JDM 🎷 Lofi artist 🏊🏻‍♂️ Swimmer