Let's discuss HashMap, LinkedHashMap, and TreeMap in Java, along with real-time examples and when to use each of them.
Blog
💛Implementation of Map Interface💚
Let's discuss HashMap, LinkedHashMap, and TreeMap in Java, along with real-time examples and when to use each of them.
It is a basic implementation of the Map interface in Java. It stores key-value pairs and uses a hash table to provide constant-time complexity for basic operations like get and put.
👉 Real-time Example:
Storing and retrieving student grades by using the student's roll number as the key and their grade as the value.
👉 Code Example:
// Creating a HashMap
Map<Integer, String> stuGrades = new HashMap<>();
// Adding data
stuGrades.put(101, "A");
stuGrades.put(102, "B");
// Retrieving data
String grade = stuGrades.get(101); // Returns "A"
👉 When to Use:
Use HashMap when you need a simple key-value store with fast retrieval and you don't require any specific order for the keys.
LinkedHashMap extends HashMap and maintains the order of elements in which they were inserted. It's implemented as a doubly-linked list with a hash table.
👉 Real-time Example:
Maintaining a shopping cart with products and their quantities, where the order of adding products matters.
👉 Code Example:
// Create a LinkedHashMap
Map<String, Integer> shoppingCart = new LinkedHashMap<>();
// Adding data
shoppingCart.put("Laptop", 2);
// Iterating in insertion order
for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
Sysout(entry.getKey()+ entry.getValue());
}
👉 When to Use:
Use LinkedHashMap when you need to maintain the order of elements as they were inserted, such as in scenarios where insertion order matters.
It is a Red-Black tree-based implementation of the Map interface. It maintains keys in sorted order, which allows for efficient range queries and ordered traversal of keys.
👉 Real-time Example:
Maintaining a dictionary of words and their meanings, where you want to look up words in alphabetical order.
👉 Code Example:
// Creating a TreeMap
Map<String, String> dictionary = new TreeMap<>();
// Adding data
dictionary.put("apple", "a fruit");
dictionary.put("banana", "a tropical fruit");
// Iterating in sorted order
for (Map.Entry<String, String> entry : dictionary.entrySet()) {
Sysout(entry.getKey()+ entry.getValue());
}
👉 When to Use:
Use TreeMap when you need to maintain keys in sorted order and perform operations like range queries or ordered traversal. Be aware that TreeMap has a slightly slower performance compared to HashMap and LinkedHashMap due to the sorting overhead.
⭐️⭐️⭐️
How to search Job in Canada: https://lnkd.in/g57PG4ZC
***
#sidpost #java #testautomation #softwaretesting #qualityassurance #software #technology
Copyright ©2024 Preplaced.in
Preplaced Education Private Limited
Ibblur Village, Bangalore - 560103
GSTIN- 29AAKCP9555E1ZV