🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In Kotlin, LinkedHashMap is a hash table and linked list implementation of the MutableMap interface. It maintains the insertion order of its elements, meaning the order in which keys are inserted is preserved. LinkedHashMap is part of the kotlin.collections package and is used for storing and managing data with efficient access, insertion, and deletion operations while maintaining order.
Table of Contents
- What is
LinkedHashMap? - Creating a
LinkedHashMap - Common Operations
- Examples of
LinkedHashMap - Real-World Use Case
- Conclusion
1. What is LinkedHashMap?
LinkedHashMap in Kotlin is a dynamic collection that allows you to store, access, and modify key-value pairs efficiently while maintaining the order of insertion. It is part of the kotlin.collections package and implements the MutableMap interface.
2. Creating a LinkedHashMap
You can create a LinkedHashMap using the constructor or by initializing it with key-value pairs.
Example
val emptyMap = LinkedHashMap<String, Int>() // Creates an empty LinkedHashMap
val mapWithElements = linkedMapOf("one" to 1, "two" to 2, "three" to 3) // Creates a LinkedHashMap with elements
3. Common Operations
LinkedHashMap supports various operations for adding, removing, and accessing key-value pairs.
Adding Elements
put(key: K, value: V): Adds a key-value pair to the map. If the key already exists, it updates the value.
Removing Elements
remove(key: K): Removes the key-value pair associated with the specified key.
Accessing Elements
get(key: K): Returns the value associated with the specified key, ornullif the key is not found.keys: Returns a set of all keys in the map.values: Returns a collection of all values in the map.entries: Returns a set of all key-value pairs in the map.
Checking Size and Emptiness
size: Returns the number of key-value pairs in the map.isEmpty(): Checks if the map is empty.isNotEmpty(): Checks if the map is not empty.
Clearing the Map
clear(): Removes all key-value pairs from the map.
4. Examples of LinkedHashMap
Example 1: Adding Elements
put(key: K, value: V)
This example demonstrates how to add key-value pairs to the map.
fun main() {
val map = LinkedHashMap<String, Int>()
map["one"] = 1
map["two"] = 2
map.put("three", 3)
println("Map after adding elements: $map") // Output: Map after adding elements: {one=1, two=2, three=3}
}
Output:
Map after adding elements: {one=1, two=2, three=3}
Example 2: Removing Elements
remove(key: K)
This example demonstrates how to remove a key-value pair from the map.
fun main() {
val map = linkedMapOf("one" to 1, "two" to 2, "three" to 3)
map.remove("two")
println("Map after removing 'two': $map") // Output: Map after removing 'two': {one=1, three=3}
}
Output:
Map after removing 'two': {one=1, three=3}
Example 3: Accessing Elements
get(key: K)
This example demonstrates how to get the value associated with a specified key.
fun main() {
val map = linkedMapOf("one" to 1, "two" to 2, "three" to 3)
println("Value for key 'one': ${map["one"]}") // Output: Value for key 'one': 1
println("Value for key 'four': ${map["four"]}") // Output: Value for key 'four': null
}
Output:
Value for key 'one': 1
Value for key 'four': null
keys, values, and entries
This example demonstrates how to access keys, values, and entries of the map.
fun main() {
val map = linkedMapOf("one" to 1, "two" to 2, "three" to 3)
println("Keys: ${map.keys}") // Output: Keys: [one, two, three]
println("Values: ${map.values}") // Output: Values: [1, 2, 3]
println("Entries: ${map.entries}") // Output: Entries: [one=1, two=2, three=3]
}
Output:
Keys: [one, two, three]
Values: [1, 2, 3]
Entries: [one=1, two=2, three=3]
Example 4: Checking Size and Emptiness
size, isEmpty(), and isNotEmpty()
This example demonstrates how to check the size of the map and if it is empty.
fun main() {
val map = linkedMapOf("one" to 1, "two" to 2, "three" to 3)
println("Size of map: ${map.size}") // Output: Size of map: 3
println("Is map empty: ${map.isEmpty()}") // Output: Is map empty: false
println("Is map not empty: ${map.isNotEmpty()}") // Output: Is map not empty: true
}
Output:
Size of map: 3
Is map empty: false
Is map not empty: true
Example 5: Clearing the Map
clear()
This example demonstrates how to remove all key-value pairs from the map.
fun main() {
val map = linkedMapOf("one" to 1, "two" to 2, "three" to 3)
map.clear()
println("Map after clearing: $map") // Output: Map after clearing: {}
}
Output:
Map after clearing: {}
5. Real-World Use Case: Maintaining Insertion Order
LinkedHashMap can be used to maintain the order of elements based on their insertion order, which is useful for ordered data representation.
Example: Maintaining Insertion Order
fun main() {
val map = LinkedHashMap<String, Int>()
map["first"] = 1
map["second"] = 2
map["third"] = 3
println("LinkedHashMap in insertion order:")
for ((key, value) in map) {
println("$key -> $value")
}
}
Output:
LinkedHashMap in insertion order:
first -> 1
second -> 2
third -> 3
Explanation:
This example shows how LinkedHashMap maintains the insertion order of elements, which can be useful for ordered data representation.
Conclusion
LinkedHashMap in Kotlin is a versatile and efficient dynamic collection from the kotlin.collections package, ideal for scenarios requiring the maintenance of insertion order. Properly utilizing LinkedHashMap can greatly enhance the performance and flexibility of your applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment