![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to work with Maps in Kotlin?
A Map is a collection where data is stored as a key-value pair and the corresponding keys have to be unique. A HashMap is a collection class based on MutableMap interface and it does that by implementing the MutableMap interface of HashTable.
Kotlin provides four types of constructors to define and manipulate a HashMap.
Example – Map Creation and Iteration in Kotlin
In this example, we will be creating a Map called "subject" and we will be iterating through it.
fun main(args: Array<String>) { // Declare HashMap var subject : HashMap<String, Int> = HashMap<String, Int> (); // Assigning value to HashMap subject.put("Java" , 1); subject.put("Kotlin" , 2); subject.put("Python" , 3); subject.put("SQL" , 4); // iterate using forEach println("------iterate using forEach Method---------
") subject.forEach { (k, v) -> println(" Subject Name -> $k and its preference -> $v") } }
Output
It will produce the following output −
------iterate using forEach Method--------- Subject Name -> Java and its preference -> 1 Subject Name -> Kotlin and its preference -> 2 Subject Name -> Python and its preference -> 3 Subject Name -> SQL and its preference -> 4
Example – Removing a value from a Map in Kotlin
In order to remove a value from a Map, we can use the remove() function.
fun main(args: Array<String>) { // Declare the HashMap var subject : HashMap<String, Int> = HashMap<String, Int> (); // Assigning value to HashMap subject.put("Java" , 1); subject.put("Kotlin" , 2); subject.put("Python" , 3); subject.put("SQL" , 4); // Remove subject.remove("SQL",4) // iterate using forEach println("------iterate using forEach Method---------
") subject.forEach { (k, v) -> println(" Subject Name -> $k and its preference -> $v") } }
Output
It will produce the following output −
------iterate using forEach Method--------- Subject Name -> Java and its preference -> 1 Subject Name -> Kotlin and its preference -> 2 Subject Name -> Python and its preference -> 3
Advertisements