Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating Map Objects
3.
Characteristics of a Map Interface
3.1.
Unique Keys
3.2.
One Null Key Allowed
3.3.
Multiple Null Values
3.4.
Not a Collection
3.5.
Order Not Guaranteed
3.6.
Methods in Java Map Interface
3.6.1.
put(K key, V value)
3.6.2.
get(Object key)
3.6.3.
remove(Object key)
3.6.4.
containsKey(Object key)
3.6.5.
containsValue(Object value)
3.6.6.
size()
3.6.7.
isEmpty()
3.6.8.
clear()
4.
HashMap
5.
LinkedHashMap
6.
TreeMap
7.
Performing Operations using Map Interface and HashMap Class
7.1.
Adding Elements
7.2.
Accessing Elements
7.3.
Removing Elements
7.4.
Iterating Over a HashMap
7.5.
Checking for a Key or Value
7.6.
Size and Clear
8.
Frequently Asked Questions
8.1.
Can a Java Map contain duplicate keys?
8.2.
How does HashMap handle null values?
8.3.
What happens if I try to get a value with a key that doesn't exist?
8.4.
Is it possible to iterate over a Map in reverse order?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Java Map

Author Gaurav Gandhi
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java Maps are fundamental tools in programming, enabling the storage and management of key-value pairs. Essentially, this means you can associate a unique key with a specific value, making data retrieval straightforward and efficient. 

Java Map

In this article, we will talk about creation of map objects, explore the characteristics of the Map interface, and examine the methods available within it. We'll also provide concrete examples using popular implementations such as HashMap, LinkedHashMap, and TreeMap. 

Creating Map Objects

To start working with maps in Java, you first need to create a map object. This is like making a new notebook where you'll write down pairs of things that belong together, like names and phone numbers. In Java, you can't create a map directly because it's an interface, which is a set of rules that classes can follow. Instead, you use specific types of maps like HashMap, LinkedHashMap, or TreeMap to make a new map. Here's how you do it:

Map<String, Integer> map = new HashMap<>();

In this line of code, we're creating a map where each key is a String (like a name) and each value is an Integer (like an age). The HashMap part tells Java we want to use a specific kind of map that's good at doing things quickly without keeping everything in order.

To put things into the map, you use the put method like this:

map.put("Alice", 30);
map.put("Bob", 25);


Now, "Alice" is linked with 30, and "Bob" is linked with 25. If you want to find out Alice's age later, you just ask the map for the value linked to "Alice".

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Characteristics of a Map Interface

Unique Keys

Each key in a Map is unique, meaning no two keys can be the same. This ensures that each key maps to exactly one value, allowing for quick and easy data retrieval. For instance, if you use student IDs as keys to store student names as values, each ID will lead to one specific student name. If you try to insert a new name using an existing ID, the old name will be replaced by the new one.

Example:

Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(1001, "John"); // Adds John to the map
studentMap.put(1002, "Doe");  // Adds Doe to the map
studentMap.put(1001, "Jane"); // Replaces John with Jane

One Null Key Allowed

A Map can include one null key, which is useful in certain situations where a key might not be available. However, only one null key is allowed, and it can map to any value.

Example:

Map<String, String> map = new HashMap<>();
map.put(null, "nullKey"); // Adds a null key with a value

Multiple Null Values

While there can be only one null key, a Map can contain multiple null values. This means different keys can point to null, indicating the absence of a value.

Example

Map<String, String> map = new HashMap<>();
map.put("Key1", null); // First null value
map.put("Key2", null); // Second null value

Not a Collection

Maps are not part of the Java Collections Framework, which includes Lists, Sets, etc. This is because Maps handle data differently, focusing on key-value pairings rather than a sequence of elements.

Order Not Guaranteed

In most Map implementations, the order of entries is not guaranteed. If maintaining the order of entries is important, you should use LinkedHashMap, which keeps the insertion order.

Example

Map<Integer, String> linkedMap = new LinkedHashMap<>();
linkedMap.put(1, "First");
linkedMap.put(2, "Second");

// Entries will be retrieved in the order they were added

Methods in Java Map Interface

The Java Map interface provides a variety of methods that allow you to work with key-value pairs effectively. Here are some of the most commonly used methods:

put(K key, V value)

This method is used to add a new key-value pair to the map. If the key already exists, the method updates the value associated with the key.

Example

Map<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 28); // Adds a new key-value pair
ageMap.put("Bob", 23);   // Adds another key-value pair
ageMap.put("Alice", 29); // Updates the value for the key "Alice"

get(Object key)

This method retrieves the value associated with the specified key. If the key does not exist, it returns null.

Example

Integer aliceAge = ageMap.get("Alice"); // Returns 29

remove(Object key)

This method removes the key-value pair associated with the specified key from the map.

Example

ageMap.remove("Bob"); // Removes the key-value pair where the key is "Bob"

containsKey(Object key)

This method checks if the map contains a specified key.

Example

boolean hasAlice = ageMap.containsKey("Alice"); // Returns true

containsValue(Object value)

This method checks if the map contains one or more keys associated with the specified value.

Example

boolean hasAge29 = ageMap.containsValue(29); // Returns true

size()

This method returns the number of key-value pairs in the map.

Example

int size = ageMap.size(); // Returns the size of the map

isEmpty()

This method checks if the map is empty.

Example

boolean isEmpty = ageMap.isEmpty(); // Returns false if the map contains key-value pairs

clear()

This method removes all the key-value pairs from the map, making it empty.

Example

ageMap.clear(); // Clears the map

These methods form the core functionality of the Map interface, enabling you to manage and manipulate key-value pairs efficiently.

Examples

Let's look into how we can use the Map interface in Java with some hands-on examples. We'll look at HashMap, LinkedHashMap, and TreeMap to see how these implementations use the Map methods we've discussed.

HashMap

HashMap is a Map implementation that allows null values and null keys. It doesn't guarantee any order for the keys or values.

Example: Creating & Using a HashMap

// Creating a HashMap

Map<String, Integer> scores = new HashMap<>();


// Adding key-value pairs to the HashMap

scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 92);


// Accessing a value

Integer aliceScore = scores.get("Alice"); // Returns 90


// Checking if a key exists

boolean hasBob = scores.containsKey("Bob"); // Returns true


// Removing a key-value pair

scores.remove("Bob");


// Checking the size

int size = scores.size(); // Returns 2 after removing Bob


// Checking if the map is empty

boolean isEmpty = scores.isEmpty(); // Returns false


// Clearing the map

scores.clear(); // All key-value pairs are removed

LinkedHashMap

LinkedHashMap extends HashMap but also maintains a linked list of the entries in the map, in the order they were inserted. This allows for predictable iteration order.

Example: Creating & Using a LinkedHashMap

// Creating a LinkedHashMap

Map<String, Integer> books = new LinkedHashMap<>();


// Adding entries

books.put("Book1", 300);
books.put("Book2", 150);
books.put("Book3", 450);


// The order in which keys were added is maintained

for (String key : books.keySet()) {
    System.out.println(key + ": " + books.get(key));
    // Outputs: Book1: 300, Book2: 150, Book3: 450
}


// Removing an entry

books.remove("Book2"); // Book2 is removed

// The remaining entries maintain their order

TreeMap

TreeMap implements the NavigableMap interface and stores its entries in a red-black tree, which means that the keys are sorted according to their natural ordering or by a specified comparator.

Example: Creating & Using a TreeMap

// Creating a TreeMap

Map<String, Integer> users = new TreeMap<>();


// Adding key-value pairs

users.put("Charlie", 10);
users.put("Alice", 5);
users.put("Bob", 20);


// Keys are sorted in natural order

for (String key : users.keySet()) {
    System.out.println(key + ": " + users.get(key));
    // Outputs: Alice: 5, Bob: 20, Charlie: 10
}


// Accessing a specific entry

Integer bobAge = users.get("Bob"); // Returns 20


// Removing an entry

users.remove("Alice");

// The remaining entries are still sorted

These examples demonstrate how the Map interface's methods are used in different implementations, each serving specific needs like order maintenance in LinkedHashMap and sorting in TreeMap.

Performing Operations using Map Interface and HashMap Class

Using the Map interface and specifically the HashMap class in Java allows you to perform a variety of operations on key-value pairs. Here, we'll explore how to use some common methods to manipulate data within a HashMap.

Adding Elements

To add elements to a HashMap, use the put method. This method takes two parameters: the key and the value. If the key already exists, the put method updates the key with the new value.

Example:

Map<String, String> capitals = new HashMap<>();
capitals.put("USA", "Washington D.C.");
capitals.put("Japan", "Tokyo");
capitals.put("Canada", "Ottawa");

Accessing Elements

You can access elements in a HashMap by using the get method and specifying the key.

Example:
String capitalOfJapan = capitals.get("Japan"); // Returns "Tokyo"

Removing Elements

To remove an element, use the remove method with the key.

Example:

capitals.remove("Canada"); // Removes the key-value pair for "Canada"

Iterating Over a HashMap

You can iterate over the keys, values, or both in a HashMap. To iterate over keys, use the keySet method. For values, use the values method. To get both keys and values, use the entrySet method.

Example: Iterating Over Keys

for (String country : capitals.keySet()) {
    System.out.println(country);
}

Example: Iterating Over Values

for (String capital : capitals.values()) {
    System.out.println(capital);
}

Example: Iterating Over Key-Value Pairs

for (Map.Entry<String, String> entry : capitals.entrySet()) {
    System.out.println("Country: " + entry.getKey() + ", Capital: " + entry.getValue());

}

Checking for a Key or Value

Use containsKey to check if a specific key exists and containsValue to see if a map contains a specific value.

Example:

boolean hasUSA = capitals.containsKey("USA"); // Returns true
boolean hasBerlin = capitals.containsValue("Berlin"); // Returns false

Size and Clear

To find out how many key-value pairs are in the map, use the size method. To remove all pairs, use clear.

Example:

int numberOfCountries = capitals.size(); // Returns the size of the map
capitals.clear(); // Clears the map

Frequently Asked Questions

Can a Java Map contain duplicate keys?

No, a Java Map cannot contain duplicate keys. Each key in a Map is unique, and adding a new key-value pair with an existing key will overwrite the existing pair's value.

How does HashMap handle null values?

HashMap allows one null key and multiple null values. If you insert a new entry with a null key, it will replace any existing entry with a null key.

What happens if I try to get a value with a key that doesn't exist?

If you try to retrieve a value using a key that isn't present in the map, the get method will return null. This is a way to check if a key exists in the map.

Is it possible to iterate over a Map in reverse order?

For HashMap and LinkedHashMap, reverse iteration isn't straightforward since these collections don't maintain a strict order. However, with TreeMap, you can iterate in reverse order by obtaining a descendingMap or using descendingKeySet.

Conclusion

In this article, we've explored the Java Map interface, focusing on its practical applications and operations. We started by understanding what Maps are and how to create them, followed by a deep dive into their characteristics and methods. Through examples, we demonstrated how to use HashMap, LinkedHashMap, and TreeMap, highlighting their unique features. Finally, we answered some common questions to clarify potential doubts. With this knowledge, you're now better equipped to utilize Java Maps effectively in your programming projects, enhancing your data management and retrieval capabilities.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.