Map in Java is an interface found in java.util package that stores data in key/value pairs. It does not permit duplicate keys. The map interface in Java needs to be more clearly understood as a subclass of the Collections interface. However, this is not the case; hence, the Java map behaves differently than the Collection interface.
Because it associates unique keys with values, you can access the latter via a map interface. The Java Map interface keeps three sets: keys, values, and key/values maps (mapping). All of these sets can be accessed independently.
The Map's Operation
Elements of a Map are stored in Java as key/value pairs. Keys are distinct values connected with specific Values.
Duplicate keys are not permitted on a map. Furthermore, each Key corresponds to a single
value.
Map-implementing classes
We cannot construct objects from Map because it is an interface. We can utilize the following classes to access Map interface functionality:
HashMap
EnumMap
LinkedHashMap
WeakHashMap
TreeMap
The Map interface is implemented by these classes described in the collection’s framework.
Hashmap
The Java collections framework's HashMap class implements the capabilities of the hash table data structure.
It organizes elements into key/value pairs. In this context, keys are unique identifiers that associate each value on a map.
The HashMap class implements the Map interface.
Example:
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
// add elements to hashmap
languages.put("Hindi", 8);
languages.put("English", 1);
languages.put("Urdu", 3);
System.out.println("HashMap: " + languages);
}
}
Output:
HashMap: {Hindi=8, English=1, Urdu=3}
Enum Map
The Java collections framework's EnumMap class provides a map implementation for enum
components.
Enum items are utilized as keys in EnumMap. It conforms to the Map interface.
We must first import the java.util to create an enum map.EnumMap package. Here's how to make enum maps in Java when we import the package.
enum Size { S, M, L, XL } EnumMap<Size, Integer> sizes = new
EnumMap<>(Size.class);
In the above example, we generated an enum map called sizes.
Here,
Size - enum keys that correspond to values
Integer - enum map values associated with the corresponding keys
Example:
import java.util.*;
public class EnumMapExample {
//Create an enum
public enum Days {
Monday, Tuesday, Wednesday, Thursday
};
public static void main(String[] args) {
//Create and populate the enum map
EnumMap<Days, String> map = new EnumMap<Months, String>(Months.class);
map.put(Months.January, "1");
map.put(Months.February, "2");
map.put(Months.March, "3");
map.put(Months.April, "4");
//Print the Map
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
January 1
February 2
March 3
April 4
Read More: Searching & Sorting Algorithms in Java
LinkedHash Map
The Java collections framework's LinkedHashMap class implements the Map interface's hash table and linked list.
The LinkedHashMap interface extends the HashMap class by storing its elements in a hash table. To order its entries, itinternally maintains a doubly-linked list among them.
We must first import the java.util to create a linked hashmap.LinkedHashMap package. Here's how to make connected hashmaps in Java when we import the library.
// LinkedHashMap with initial capacity eight and load
factor 0.6 LinkedHashMap<Key, Value> numbers = new
LinkedHashMap<>(8, 0.6f);
In the preceding code, we established a linked hashmap called numbers.
Here,
Key- A key is a unique identifier that is used to link each element (value) in a map.
Value - Values are the items on a map that are related to the keys.
Example:
import java.util.*;
class LinkedHashMap1{
public static
void main(String args[]){
LinkedHashMap<Integer,String> hm=new
LinkedHashMap<Integer,String>();
hm.put(10,"Sun");
hm.put(11,"Earth");
hm.put(12,"Moon");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
10 Sun
11 Earth
12 Moon
WeakHash Map
The Java collections framework's WeakHashMap class implements the hash table data structure. It conforms to the Map interface. If a weak reference type object is no longer used in
the programme, it can be garbage collected in Java.
First, let's learn how to make a weak hash map. Then we'll see how it's different from a hashmap.
We must first import the java.util to create a weak hashmap.WeakHashMap package. Here's how to make weak hashmaps in Java when we import the library.
//WeakHashMap creation with capacity eight and load factor 0.6
WeakHashMap<Key, Value> numbers = new
WeakHashMap<>(8, 0.6);
In the preceding code, we generated a weak hashmap called numbers.
Here,
Key - A key is a unique identifier that is used to link each element (value) in a map.
Value - elements of a map that are linked by keys
Example:
import java.util.*;
public class WeakHashMap_Demo {
private static Map map;
public static void main (String args[]) {
map = newWeakHashMap();
map.put(new String("Maine"), "Augusta");
Runnablerunner = new Runnable() {
Public void run() {
while (map.containsKey("Maine")) {
try {
Thread.sleep(500);
}
catch (InterruptedException ignored) {
}
System.out.println("High waiting");
System.gc();
}
}
};
Thread t = new Thread(runner);
t.start();
System.out.println("Key waiting");
try {
t.join();
} catch
(InterruptedException ignored) {
}
}
}
Output:
High waiting
Key waiting
TreeMap
The Java collections framework's TreeMap class implements the tree data structure. It conforms to the NavigableMap interface.
To create a TreeMap, we must first import the java.util.TreeMap package. Here's how to make a TreeMap in Java after we import the package.
TreeMap<Key, Value> numbers = new
TreeMap<>();
We constructed a TreeMap named numbers in the above code without any arguments. In this scenario, the TreeMap items are ordered organically (in ascending order).
The Comparator interface, on the other hand, allows us to customize the sorting of components.
Here,
Key - A key is a unique identifier that is used to link each element (value) in a map.
Value - elements of a map that are linked by keys
Example:
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new
TreeMap<Integer,String>();
map.put(1,"Jay");
map.put(2,"Amit");
map.put(3,"Kapil");
map.put(4,"Muskan");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+""+m.getValue());
}
}
}
Output:
1 Jay
2 Amit
3 Kapil
4 Muskan
How Do I Use a Map in java?
To utilize Map in Java, we must first import the java.util.Map package. Here's how we can make a map after we import the package.
// Map
implementation using HashMap
Map< Key,
Value> numbers = new HashMap<>();
In the preceding code, we constructed a Map called numbers. To implement the Map interface, we used the HashMap class.
Here,
Key - A key is a unique an identifier that links each element (value) in a map.
Value - elements of a map that are linked by keys
Map Methodologies
The Map interface contains all of the Collection interface's functions. This is because Collection is a super interface of Map.
The Map interface, in addition to the methods provided in the Collection interface, adds the following ways:
put(K, V) - Inserts a key K and a value V association into the Map. If the Key already exists, the new value takes the place of the old one.
putAll() - Puts all the entries from the supplied Map into this Map.
putIfAbsent(K, V) - If the key K is not already connected with the value V, putIfAbsent(K, V) inserts the association.
get(K) - Returns the value corresponding to the supplied Key K. If the Key cannot be located, it returns null.
getOrDefault(K, defaultValue) – Returns the value associated with key K. If the Key cannot be found, the defaultValue is returned.
containsKey(K) - Determines whether or not the provided key K is present in the Map.
containsValue(V) - Determines whether or not the specified value V exists in the Map.
replace(K, V) - Replaces the value of the key K with the new value V provided.
replace(K, oldValue, newValue) – Replaces the value of the key K with the new value newValue only if the key K is related with the value oldValue.
remove(K) - Removes the map entry represented by the key K.
remove(K, V) - Removes the entry from the Map that has key K and value V connected with it.
keySet() - Returns a collection of all the keys in a map.
values() - Returns a collection of all the values in a map.
entrySet() - Returns a collection of all the key/value mappings in a map.
Example:
Implementation of HashMap Class
import java.util.Map;
import java.util.HashMap;
class Main {
Public static void main(String[] args) {
// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();
//Insert elements to the map
numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);
// Access keys of the map
System.out.println("Keys: " + numbers.keySet());
// Access values of the map
System.out.println("Values: " + numbers.values());
// Access entries of the map
System.out.println("Entries: " + numbers.entrySet());
//Remove Elements from the Map
int value = numbers.remove("Two");
System.out.println("Removed Value: " + value);
}
}
Map: {One=1, Two=2}
Keys: [One, Two]
Values: [1, 2]
Entries: [One=1, Two=2]
Removed Value: 2
Example: Implementation of TreeMap Class
import java.util.Map;
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
// Creating Map using TreeMap
Map<String, Integer> values = new TreeMap<>();
// Insert elements to map
values.put("Second", 2);
values.put("First", 1);
System.out.println("Map using TreeMap: " + values);
//Replacing the values
values.replace("First", 11);
values.replace("Second",22);
System.out.println("New Map: " + values);
// Remove elements from the Map
int removedValue = values.remove("First");
System.out.println("Removed Value: " + removedValue);
}
}
Output:
Map using TreeMap: {First=1, Second=2}
New Map: {First=11, Second=22}
Removed Value: 11
Features of Maps in Java
Java maps are data structures that enable the efficient storage and retrieval of key-value pairs. They have several key qualities that make them effective tools for managing data collections in Java applications:
Key-Value Storage: Java maps enable data storage as key-value pairs, with each key being unique within the Map. This enables efficient and fast retrieval of data based on their related keys, making maps suited for applications requiring quick lookups.
Java maps are dynamic in size, meaning they can expand or contract based on the number of key-value pairs stored in them. This allows them to handle different volumes of data without having to pre-allocate memory.
Java maps provide a variety of implementations, including HashMap, TreeMap, and LinkedHashMap, each with its own set of features. HashMap provides constant time complexity for most operations and is suitable for general-purpose use, TreeMap keeps keys in sorted order and is useful when keys need to be sorted, and LinkedHashMap keeps key insertion order and is ideal for scenarios where key insertion order is important.
Java maps offer quick retrieval of values based on their keys, often with constant time complexity, making them useful for seeking up values in big collections of data.
Versatility in Key and Value: Java maps allow any object to be used as a key or a value, allowing for greater versatility in the data types that can be stored. As a result, maps can be used for a wide range of applications, from simple data types to complex bespoke objects.
Rich Functionality: Java maps provide a wide range of functionality, including the ability to add, retrieve, update, and remove key-value pairs, search for keys or values, iterate through entries, and perform operations on the keys or values as a whole. They also include techniques for dealing with null keys and values, detecting the presence of keys and values, and managing concurrent access in multi-threaded contexts.
Java maps enable customization via methods such as equals() and hashCode(), which can be changed in custom objects used as keys. This enables fine-grained control over how keys are compared and hashed, allowing customized behaviour to meet specific needs.
Thread-Safe Implementations: Thread-safe implementations of Java maps, such as ConcurrentHashMap, provide concurrent access from many threads without the need for external synchronization. As the result, they are appropriate for multi-threaded situations where concurrent access is an issue.
In summary, Java maps include significant characteristics such as key-value storage, dynamic size, multiple implementations, quick retrieval, Key and value type flexibility, comprehensive
functionality, customizability, and thread safety. These characteristics make Java maps versatile and efficient tools for handling data sets in java applications.
Applications of Maps in Java
Maps in Java are versatile data structures that can be used in various software development scenarios. Maps are commonly used in the following Java applications:
Maps are often used to store and retrieve data as key-value pairs. They can be used to store configuration settings, cache data, or manage user preferences, for example, with the keys representing data identifiers and the values representing the relevant data.
Database Operations: Maps can map database query results to relevant keys, making the retrieved data easier to manage and analyze. Maps can also represent database tables, with the keys corresponding to the primary keys and the values corresponding to the row data.
Algorithm and data processing: Activities typically involve maps. Maps can, for example, be used to implement graph algorithms, where nodes are represented as keys and edges as values or to count the occurrences of elements in a dataset, where elements are keys and counts are values.
Caching: Maps can be used as a cache to store frequently requested data to get it faster. To increase efficiency and reduce resource utilization; maps can be used to construct a cache for storing the results of expensive calculations, often-accessed resources, or frequently utilized data from external sources, such as online APIs.
User Input and Interaction: Maps can be used in Java programmes to handle user input and interaction. Maps, for example, can be used to store user preferences, form or dialogue input data, or manage state information during user interactions, such as handling session data online
applications.
Localization and internationalization: Maps can be used in internationalized Java applications to store localized messages, labels, or other resources. Maps can hold key-value pairs that provide translations for several languages or localities, making it simple to access
the appropriate localized resources based on the user's locale or language preference.
Conclusion
Finally, Java maps are strong data structures that allow you to store and retrieve key-value pairs effectively. They provide a versatile and dynamic approach to expressing object relationships, making them a vital feature in many Java applications.
Java maps are available in a variety of implementations, including HashMap, TreeMap, and LinkedHashMap, each with its own set of properties and use cases. HashMap provides constant time complexity for most operations and is suitable for general-purpose use; TreeMap keeps keys in sorted order and is useful when keys need to be sorted, and LinkedHashMap keeps key insertion order and is ideal for scenarios where key insertion order is important.
Java maps provide a wide range of capabilities, including the ability to add, retrieve, update, and remove key-value pairs, as well as search for keys or values, iterate through entries, and perform operations on the keys or values as a whole. They also include techniques for
dealing with null keys and values, detecting the presence of keys and values, and managing concurrent access in multi-threaded contexts.
When utilizing Java maps, it is critical to examine variables such as performance, memory utilization, and thread safety, and to select the best implementation based on your application's specific requirements. It's also critical to avoid issues like hash collisions, which
can degrade performance, and to appropriately override the equals() and hashCode() methods for custom objects used as keys.
To summarise, Java maps are a versatile and powerful tool for handling key-value pairs collections in Java applications. They provide flexibility, efficiency, and ease of use for many use cases due to their large range of implementations and capabilities. Understanding their abilities, qualities, and recommended practices for utilization can significantly improve your Java programmes' efficiency and functionality.
Also Read: Set in Java: Methods and Operations
Comments