In Kotlin, a HashMap is a collection that stores key-value pairs, where each key must be unique, but values can be duplicated. It is a hash table based implementation of the MutableMap interface. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key, value> or HashMap<K, V>. The hash table based implementation of HashMap does not guarantees about the order of specified data of key, value and entries of collections.
Constructors of HashMap in Kotlin -
Kotlin provides four public constructors to create a HashMap:
1. HashMap() :
It is the default constructor which constructs an empty HashMap instance.
val hashMap = HashMap<String, Int>()
println("Empty HashMap: $hashMap")
2. HashMap(initialCapacity: Int) :
It is used to construct a HashMap of specified initial capacity. If initialCapacity isn't being used then it will get ignored.
val hashMap = HashMap<String, Int>(10)
3. HashMap(initialCapacity: Int, loadFactor: Float = 0f) :
It is used to construct a HashMap of specified initial capacity and load factor. If initialCapacity and loadFactor isn't being used then both will get ignored.
Note: loadFactor is ignored in Kotlin's current implementation.
4. HashMap(original: Map <out K, V> ) :
It creates instance of HashMap with same mappings as specified map.
val original = mapOf("IronMan" to 3000, "Thor" to 100)
val copyMap = HashMap(original)
println(copyMap)
Important functions of HashMap in Kotlin -
Function | Description |
---|
put(key, value) | Inserts or updates the value for the given ke |
get(key) | Returns the value for the key or null if not found. |
remove(key) | Removes the key-value pair for the given key. |
containsKey(key) | Returns true if the map contains the given key. |
containsValue(value) | Returns true if the map contains the given value. |
clear() | Removes all entries from the map. |
size | Returns the number of key-value pairs in the map. |
replace(key, value) | Replaces the value for the given key if it exists. |
Use of HashMap Functions -
HashMap(), HashMap(original: Map), Traversing hashmap, HashMap.get() -
Kotlin
fun main() {
// Initialize HashMap with empty "HashMap of <String, Int>"
var hashMap : HashMap<String, Int> = HashMap<String, Int> ()
// print the empty hashMap
printHashMap(hashMap)
// use put() to add elements
hashMap.put("IronMan" , 3000)
hashMap.put("Thor" , 100)
hashMap.put("SpiderMan" , 1100)
hashMap.put("NickFury" , 1200)
hashMap.put("HawkEye" , 1300)
// print the non-empty hashMap
printHashMap(hashMap)
println("hashMap : " + hashMap + "\n")
// travarse hashMap using for loop
for(key in hashMap.keys){
println("Element at key $key : ${hashMap[key]}")
}
// creating another hashMap object with the previous version of hashMap object
var secondHashMap : HashMap<String, Int> = HashMap<String, Int> (hashMap)
println("\n" + "Second HashMap : ")
for(key in secondHashMap.keys){
//using hashMap.get() function to fetch the values
println("Element at key $key : ${hashMap.get(key)}")
}
//this will clear the whole map and make it empty
println("hashMap.clear()")
hashMap.clear()
println("After Clearing : " + hashMap)
}
// function to print the hashMap
fun printHashMap(hashMap : HashMap<String, Int>){
// isEmpty() function to check whether the hashMap is empty or not
if(hashMap.isEmpty()){
println("hashMap is empty")
}else{
println("hashMap : " + hashMap)
}
}
Output :
hashMap is empty : {}
hashMap : {Thor=100, HawkEye=1300, NickFury=1200, IronMan=3000, SpiderMan=1100}
hashMap : {Thor=100, HawkEye=1300, NickFury=1200, IronMan=3000, SpiderMan=1100}
Element at key Thor : 100
Element at key HawkEye : 1300
Element at key NickFury : 1200
Element at key IronMan : 3000
Element at key SpiderMan : 1100
secondHashMap :
Element at key Thor : 100
Element at key HawkEye : 1300
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100
hashMap.clear()
After Clearing : {}
HashMap initial capacity, HashMap.size -
Kotlin
fun main() {
// HashMap can also be initialize with its initial capacity.
// The capacity can be changed by adding and replacing its element.
var hashMap : HashMap<String, Int> = HashMap<String, Int> (4)
// use put() to add elements
hashMap.put("IronMan" , 3000)
hashMap.put("Thor" , 100)
hashMap.put("SpiderMan" , 1100)
hashMap.put("NickFury" , 1200)
for(key in hashMap.keys) {
println("Element at key $key : ${hashMap[key]}")
}
// returns the size
println("\n" + "hashMap.size : " + hashMap.size )
// add new element
hashMap["BlackWidow"] = 1000;
println("hashMap.size : " + hashMap.size + "\n")
for(key in hashMap.keys) {
println("Element at key $key : ${hashMap[key]}")
}
}
Output:
Element at key Thor : 100
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100
hashMap.size : 4
hashMap.size : 5
Element at key Thor : 100
Element at key BlackWidow : 1000
Element at key IronMan : 3000
Element at key NickFury : 1200
Element at key SpiderMan : 1100
HashMap.get(key), HashMap.replace(), HashMap.put() -
Kotlin
fun main() {
var hashMap : HashMap<String, Int> = HashMap<String, Int> ()
// using put() function to add elements
hashMap.put("IronMan" , 3000)
hashMap.put("Thor" , 100)
hashMap.put("SpiderMan" , 1100)
hashMap.put("Cap" , 1200)
for(key in hashMap.keys) {
println("Element at key $key : ${hashMap[key]}")
}
// access elements
println("\nhashMap[\"IronMan\"] : " + hashMap["IronMan"])
hashMap["Thor"] = 2000
println("hashMap.get(\"Thor\") : " + hashMap.get("Thor") + "\n")
// replacing values
hashMap.replace("Cap" , 999);
hashMap.put("Thor" , 2000);
println("hashMap.replace(\"Cap\" , 999)" + " hashMap.replace(\"Thor\" , 2000)) :")
for(key in hashMap.keys) {
println("Element at key $key : ${hashMap[key]}")
}
}
Output:
Element at key Thor : 100
Element at key Cap : 1200
Element at key IronMan : 3000
Element at key SpiderMan : 1100
hashMap["IronMan"] : 3000
hashMap.get("Thor") : 2000
hashMap.replace("Cap", 999) hashMap.replace("Thor", 2000)) :
Element at key Thor : 2000
Element at key Cap : 999
Element at key IronMan : 3000
Element at key SpiderMan : 1100
Time complexity of HashMap -
Kotlin HashMap provides constant time or O(1) complexity for basic operations like get and put, if hash function is properly written and it disperses the elements properly. In case of searching in the HashMap containsKey() is just a get() that throws away the retrieved value, it's O(1) (assuming the hash function works properly).
Some other functions of Kotlin HashMap class -
- Boolean containsKey(key: K): It returns true if map contains specifies key.
- Boolean containsValue(value: V): It returns true if map maps one of more keys to specified value.
- void clear(): It removes all elements from map.
- remove(key: K): It removes the specified key and its corresponding value from map
In Kotlin, a HashMap is a collection that stores key-value pairs. Each key in a HashMap must be unique, but values can be duplicated. The HashMap class provides methods for adding, removing, and retrieving elements, as well as checking if a key or value is present in the map.
Example of using HashMap in Kotlin:
Kotlin
fun main() {
// create a new HashMap
val myMap = hashMapOf<String, Int>()
// add elements to the HashMap
myMap.put("apple", 1)
myMap.put("banana", 2)
myMap.put("orange", 3)
// print the HashMap
println(myMap)
// remove an element from the HashMap
myMap.remove("banana")
// print the updated HashMap
println(myMap)
// check if a key is present in the HashMap
val containsKey = myMap.containsKey("apple")
println("Contains key 'apple': $containsKey")
// check if a value is present in the HashMap
val containsValue = myMap.containsValue(3)
println("Contains value 3: $containsValue")
}
Output:
{apple=1, banana=2, orange=3}
{apple=1, orange=3}
Contains key 'apple': true
Contains value 3: true
In this example, we create a new HashMap with String keys and Int values. We then add three key-value pairs to the HashMap using the put() method. Next, we print the entire HashMap using the println() function. We then remove the key-value pair with the key "banana" using the remove() method and print the updated HashMap. Finally, we use the containsKey() and containsValue() methods to check if the HashMap contains the key "apple" and the value 3, respectively.
Advantages of HashMap:
- HashMap provides a flexible way to store key-value pairs and is easy to use.
- HashMap provides efficient O(1) time complexity for basic operations such as adding, removing, and retrieving elements.
- HashMap can be used to store a wide variety of data types, including user-defined objects.
Disadvantages of HashMap:
- HashMap uses more memory than some other data structures because it stores both keys and values.
- HashMap is not thread-safe by default, so concurrent access to a HashMap can cause data corruption or unexpected behavior. If you need to access a HashMap from multiple threads, you should use a thread-safe implementation or use synchronization to ensure thread safety.
- The order of elements in a HashMap is not guaranteed, which can be a disadvantage in some cases where element ordering is important. If you need to maintain a specific order of elements, you should use a different data structure such as a LinkedHashMap.
Similar Reads
Kotlin Tutorial
This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Overview
Introduction to Kotlin
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, which has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 as a new language for the JVM. Kotlin is an object-oriented language, and a better lang
4 min read
Kotlin Environment setup for Command Line
To set up a Kotlin environment for the command line, you need to do the following steps:Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin com
2 min read
Kotlin Environment setup with Intellij IDEA
Kotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully i
2 min read
Hello World program in Kotlin
Hello, World! It is the first basic program in any programming language. Let's write the first program in the Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor, Notepad or Notepad++, and create a file named firstapp.kt with the following code. // Kotlin He
2 min read
Basics
Kotlin Data Types
The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects.There are different data types
3 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. The declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type o
2 min read
Kotlin Operators
Operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example:Kotlinfun main(args: Array<String>) { var a= 10 + 20 println(a) }Output:30Explanation: Here, â+â is an additio
4 min read
Kotlin Standard Input/Output
In this article, we will discuss how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow a sequence of bytes or byte streams from an input device, such as a Keyboard, to the main memory of the system and from main memory to an out
4 min read
Kotlin Type Conversion
Type conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type. As we know Java supports implicit type conversion from smaller to larger data types. An integer value can be assigned to the long data type. Example: Javapublic class Typecas
2 min read
Kotlin Expression, Statement and Block
Every Kotlin program is made up of parts that either calculate values, called expressions, or carry out actions, known as statements. These parts can be organized into sections called blocks. Table of ContentKotlin ExpressionKotlin StatementKotlin BlockKotlin ExpressionAn expression in Kotlin is mad
4 min read
Control Flow
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If t
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines.While loopIt cons
2 min read
Kotlin do-while loop
Like Java, the do-while loop is a control flow statement that executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, depending on a Boolean condition at the end of the do-while block. It contrasts with the while loop because the while l
2 min read
Kotlin for loop
In Kotlin, the for loop is equivalent to the foreach loop of other languages like C#. Here for loop is used to traverse through any data structure that provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of the for loop in Kot
4 min read
Kotlin when expression
In Kotlin, when replaces the switch operator of other languages like Java. A certain block of code needs to be executed when some condition is fulfilled. The argument of when expression compares with all the branches one by one until some match is found. After the first match is found, it reaches to
6 min read
Kotlin Unlabelled break
When we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expre
4 min read
Kotlin labelled continue
In this article, we will learn how to use continue in Kotlin. While working with a loop in programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. continue is used to repeat the loop for a specific condition.
4 min read
Functions
Kotlin functions
In Kotlin, functions are used to encapsulate a piece of behavior that can be executed multiple times. Functions can accept input parameters, return values, and provide a way to encapsulate complex logic into reusable blocks of code. Table of ContentWhat are Functions?Example of a FunctionTypes of Fu
7 min read
Kotlin Default and Named argument
In most programming languages, we need to specify all the arguments that a function accepts while calling that function, but in Kotlin, we need not specify all the arguments that a function accepts while calling that function, so it is one of the most important features. We can get rid of this const
7 min read
Kotlin Recursion
In this tutorial, we will learn about Kotlin Recursive functions. Like other programming languages, we can use recursion in Kotlin. A function that calls itself is called a recursive function, and this process of repetition is called recursion. Whenever a function is called then there are two possib
3 min read
Kotlin Tail Recursion
In a traditional recursion call, we perform our recursive call first, and then we take the return value of the recursive call and calculate the result. But in tail recursion, we perform the calculation first, and then we execute the recursive call, passing the results of the current step to the next
2 min read
Kotlin Lambdas Expressions and Anonymous Functions
In this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features. Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immedi
6 min read
Kotlin Inline Functions
In Kotlin, higher-order functions and lambda expressions are treated like objects. This means they can use up memory, which can slow down your program. To help with this, we can use the 'inline' keyword. This keyword tells the compiler not to create separate memory spaces for these functions. Instea
5 min read
Kotlin infix function notation
In this article, we will learn about infix notation used in Kotlin functions. In Kotlin, a function marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in KotlinTable of ContentStandard libr
5 min read
Kotlin Higher-Order Functions
Kotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. Higher-Order FunctionIn Kotlin, a function that can accept a function as a parameter or return a func
6 min read
Collections
Kotlin Collections
In Kotlin, collections are used to store and manipulate groups of objects or data. There are several types of collections available in Kotlin, including:Collection NameDescriptionLists Ordered collections of elements that allow duplicates.Sets Unordered collections of unique elements.Maps Collection
6 min read
Kotlin list : Arraylist
The ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as a prerequisite. It also provides read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature. We use ArrayList to acce
6 min read
Kotlin list : listOf()
In Kotlin, listOf() is a function that is used to create an immutable list of elements. The listOf() function takes a variable number of arguments and returns a new list containing those arguments. Here's an example: Kotlin val numbers = listOf(1, 2, 3, 4, 5) In this example, we create a new list ca
8 min read
Kotlin Set : setOf()
In Kotlin, a Set is a generic unordered collection of elements that does not allow duplicate elements. Kotlin provides two main types of sets:Immutable Set: Created using setOf() â supports only read-only operations.Mutable Set: Created using mutableSetOf() â supports both read and write operations.
4 min read
Kotlin hashSetOf()
In Kotlin, a HashSet is a generic, unordered collection that holds unique elements only. It does not allow duplicates and provides constant-time performance for basic operations like add, remove, and contains, thanks to its internal hashing mechanism. The hashSetOf() function in Kotlin creates a mut
4 min read
Kotlin Map : mapOf()
In Kotlin, a Map is a collection that stores data in key-value pairs. Each key in a map is unique, and the map holds only one value for each key. If a key is repeated, only the last value is retained.Kotlin distinguishes between:Immutable maps (mapOf()) - read-onlyMutable maps (mutableMapOf()) - rea
5 min read
Kotlin Hashmap
In Kotlin, a HashMap is a collection that stores key-value pairs, where each key must be unique, but values can be duplicated. It is a hash table based implementation of the MutableMap interface. Map keys are unique and the map holds only one value for each key. It is represented as HashMap<key,
7 min read
OOPs Concept
Kotlin Class and Objects
In Kotlin, classes and objects are used to represent objects in the real world. A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or fields), and implementations of behavior (member functions or methods). An object is an i
4 min read
Kotlin Nested class and Inner class
In Kotlin, you can define a class inside another class. Such classes are categorized as either nested classes or inner classes, each with different behavior and access rules.Nested ClassA nested class is a class declared inside another class without the inner keyword. By default, a nested class does
3 min read
Kotlin Setters and Getters
Properties are an important part of any programming language. In Kotlin, we can define properties in the same way as we declare another variable. Kotlin properties can be declared either as mutable using the var keyword or as immutable using the val keyword. Syntax of Property var <propertyName
5 min read
Kotlin | Class Properties and Custom Accessors
The basic and most important idea of a class is Encapsulation. It is a property to encapsulate code and data, into a single entity. In Java, the data are stored in the fields and these are mostly private. So, accessor methods - a getter and a setter are provided to let the clients of the given class
2 min read
Kotlin Constructor
A constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. Kotlin has two types of co
7 min read
Kotlin Visibility Modifiers
In Kotlin, visibility modifiers are used to control the visibility of a class, its members (properties, functions, and nested classes), and its constructors. The following are the visibility modifiers available in Kotlin: private: The private modifier restricts the visibility of a member to the cont
6 min read
Kotlin Inheritance
Kotlin supports inheritance, which allows you to define a new class based on an existing class. The existing class is known as the superclass or base class, and the new class is known as the subclass or derived class. The subclass inherits all the properties and functions of the superclass, and can
10 min read
Kotlin Interfaces
In Kotlin, an interface is a collection of abstract methods and properties that define a common contract for classes that implement the interface. An interface is similar to an abstract class, but it can be implemented by multiple classes, and it cannot have state. Interfaces are custom types provid
7 min read
Kotlin Data Classes
We often create classes to hold some data in it. In such classes, some standard functions are often derivable from the data. In Kotlin, this type of class is known as data class and is marked as data. Example of a data : data class Student(val name: String, val roll_no: Int) The compiler automatical
4 min read
Kotlin Sealed Classes
Kotlin introduces a powerful concept that doesn't exist in Java: sealed classes. In Kotlin, sealed classes are used when you know in advance that a value can only have one of a limited set of types. They let you create a restricted class hierarchy, meaning all the possible subclasses are known at co
4 min read
Kotlin Abstract class
In Kotlin, an abstract class is a class that cannot be instantiated and is meant to be subclassed. An abstract class may contain both abstract methods (methods without a body) and concrete methods (methods with a body). An abstract class is used to provide a common interface and implementation for i
5 min read
Enum Classes in Kotlin
In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants. In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that somet
5 min read
Kotlin extension function
Kotlin gives the programmer the ability to add more functionality to the existing classes, without inheriting them. This is achieved through a feature known as extensions. When a function is added to an existing class it is known as Extension Function. To add an extension function to a class, define
5 min read
Kotlin generics
Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check on the compile-time type safety. Creating parameterized classes - A generic type is a class or method that is parameterized over types. We
6 min read