
- Android Basics
- Android - Home
- Android - Overview
- Android - Environment Setup
- Android - Architecture
- Android - Application Components
- Android - Hello World Example
- Android - Resources
- Android - Activities
- Android - Services
- Android - Broadcast Receivers
- Android - Content Providers
- Android - Fragments
- Android - Intents/Filters
- Android - User Interface
- Android - UI Layouts
- Android - UI Controls
- Android - Event Handling
- Android - Styles and Themes
- Android - Custom Components
- Android Advanced Concepts
- Android - Drag and Drop
- Android - Notifications
- Location Based Services
- Android - Sending Email
- Android - Sending SMS
- Android - Phone Calls
- Publishing Android Application
- Android Useful Examples
- Android - Alert Dialoges
- Android - Animations
- Android - Audio Capture
- Android - AudioManager
- Android - Auto Complete
- Android - Best Practices
- Android - Bluetooth
- Android - Camera
- Android - Clipboard
- Android - Custom Fonts
- Android - Data Backup
- Android - Developer Tools
- Android - Emulator
- Android - Facebook Integration
- Android - Gestures
- Android - Google Maps
- Android - Image Effects
- Android - ImageSwitcher
- Android - Internal Storage
- Android - JetPlayer
- Android - JSON Parser
- Android - Linkedin Integration
- Android - Loading Spinner
- Android - Localization
- Android - Login Screen
- Android - MediaPlayer
- Android - Multitouch
- Android - Navigation
- Android - Network Connection
- Android - NFC Guide
- Android - PHP/MySQL
- Android - Progress Circle
- Android - ProgressBar
- Android - Push Notification
- Android - RenderScript
- Android - RSS Reader
- Android - Screen Cast
- Android - SDK Manager
- Android - Sensors
- Android - Session Management
- Android - Shared Preferences
- Android - SIP Protocol
- Android - Spelling Checker
- Android - SQLite Database
- Android - Support Library
- Android - Testing
- Android - Text to Speech
- Android - TextureView
- Android - Twitter Integration
- Android - UI Design
- Android - UI Patterns
- Android - UI Testing
- Android - WebView Layout
- Android - Wi-Fi
- Android - Widgets
- Android - XML Parsers
- Android Useful Resources
- Android - Questions and Answers
- Android - Useful Resources
- Android - Discussion
How to iterate over a Hashmap in Kotlin?
A Map is a collection where data is stored as a key-value pair and the corresponding key has to be unique. A HashMap is a collection class based upon MutableMap interface and it does that by implementing MutableMap interface of HashTable. Kotlin provides four types of constructor to define and manipulate HashMap.
HashMap() – It is the default constructor which helps us create an empty HashMap.
HashMap(initialCapacity: Int, loadFactor: Float = 0f) – It helps us create a HashMap using initial capacity; if it is not provided, then it will be ignored and it will act as default HashMap().
HashMap(initialCapacity: Int) – It helps us create a HashMap with the given capacity.
HashMap(original: Map <out K, V>) – It creates an instance of HashMap as specified in the Map.
Here, we will be using HashMap() constructor to create a HashMap and its corresponding Put() to populate the same with some key-value data. In this example, we will create a collection of "subject" which will hold the subject name and our personal preference number. We will iterate through this HashMap using different options available in the Kotlin library.
Iterate Using for() Loop
In conventional programming languages, we have the for() loop to traverse through any of the collection. In the following example, we will traverse through the Map using for() loop.
Example
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("C++" , 4); subject.put("SQL" , 5); //iterate through for loop println("---------iterate using for Loop------------
") for ((k, v) in subject) { println(" Subject Name -> $k and its preference -> $v") } println("
") }
Output
Once you execute the code, it will generate the following output −
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar ---------iterate using for Loop------------ Subject Name -> Java and its preference -> 1 Subject Name -> C++ and its preference -> 4 Subject Name -> Kotlin and its preference -> 2 Subject Name -> Python and its preference -> 3 Subject Name -> SQL and its preference -> 5
Iterate using ForEach() Loop
Besides for() loop, we can also use ForEach() to propagate through a collection. In the following example, we will traverse through the Map using forEach() loop.
Example
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("C++" , 4); subject.put("SQL" , 5); //iterate using forEach println("------iterate using forEach Method---------
") subject.forEach { (k, v) -> println(" Subject Name -> $k and its preference -> $v") } println("
") }
Output
Once you execute the code, it will produce the following output −
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar ------iterate using forEach Method--------- Subject Name -> Java and its preference -> 1 Subject Name -> C++ and its preference -> 4 Subject Name -> Kotlin and its preference -> 2 Subject Name -> Python and its preference -> 3 Subject Name -> SQL and its preference -> 5
Using iterator() Method
Apart from the above conventional ways of traversing a collection, the Kotlin standard library also provides a function called iterator() that we can use to access objects in a collection without exposing the value of the same. This is the most efficient way of accessing all the values of a collection. In the following example, we will traverse the Hashmap using the iterator() method.
Example
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("C++" , 4); subject.put("SQL" , 5); //using iterator() method println("-----------Using iterator() Method-----------
") val i = subject.keys.iterator() while (i.hasNext()) { val key = i.next() val value = subject[key] println("Subject Name -> ${key} and its preference -> $value") } }
Output
Once you execute the code, it will generate the following output −
$kotlinc -nowarn main.kt -include-runtime -d main.jar $java -Xmx128M -Xms16M -jar main.jar -----------Using iterator() Method----------- Subject Name -> Java and its preference -> 1 Subject Name -> C++ and its preference -> 4 Subject Name -> Kotlin and its preference -> 2 Subject Name -> Python and its preference -> 3 Subject Name -> SQL and its preference -> 5
- Related Articles
- Java Program to Iterate over a HashMap
- How to iterate over a list in Java?
- How to iterate over a Java list?
- How to iterate over a C# dictionary?
- How to iterate over a C# list?
- How to iterate over a C# tuple?
- How to iterate over rows in a DataFrame in Pandas?
- How to iterate a JSON Array in Android using Kotlin?
- How to iterate over all MongoDB databases?
- How can I save a HashMap to Sharedpreferences in Android Kotlin?
- Iterate over a dictionary in Python
- Iterate over a list in Python
- Iterate over a set in Python
- Java Program to Iterate over a Set
- C++ Program to Iterate Over a Dictionary
