Java is a popular programming language used in various applications. One of its key features is the Map interface, which allows developers to store key-value pairs. In this article, we will discuss Java Map and provide some examples of its use.
Table of Contents
Table of Contents
Introduction
Java is a popular programming language used in various applications. One of its key features is the Map interface, which allows developers to store key-value pairs. In this article, we will discuss Java Map and provide some examples of its use.
What is Java Map?
Java Map is an interface in the Java Collections Framework that stores key-value pairs. The keys and values can be of any type, and the keys are unique. It provides methods to add, remove, and retrieve elements from the map.
Types of Java Map
There are three types of Java Map:
- HashMap: stores key-value pairs in an unordered manner
- TreeMap: stores key-value pairs in a sorted manner based on the keys
- LinkedHashMap: stores key-value pairs in the order they were inserted
Java Map Example Code
Let's take a look at some examples of how to use Java Map:
Example 1: Creating a HashMap
The following code creates a HashMap and adds key-value pairs:
Map map = new HashMap<>(); map.put("John", 25); map.put("Mary", 30); map.put("Bob", 35);
Example 2: Retrieving a Value
The following code retrieves a value from a HashMap:
int age = map.get("Mary"); System.out.println("Mary's age is " + age);
Example 3: Removing a Key-Value Pair
The following code removes a key-value pair from a HashMap:
map.remove("Bob");
Example 4: Iterating over a Map
The following code iterates over a HashMap:
for (Map.Entry entry : map.entrySet()) { String name = entry.getKey(); int age = entry.getValue(); System.out.println(name + " is " + age + " years old"); }
Conclusion
Java Map is a useful interface for storing key-value pairs. It provides methods to add, remove, and retrieve elements from the map. There are different types of Java Map, such as HashMap, TreeMap, and LinkedHashMap. By using Java Map, developers can efficiently manage and manipulate data in their applications.
Question & Answer
Q: What is the difference between HashMap and TreeMap?
A: HashMap stores key-value pairs in an unordered manner, while TreeMap stores key-value pairs in a sorted manner based on the keys.
Q: Can keys and values be of any type in Java Map?
A: Yes, keys and values can be of any type in Java Map.
Q: What is the purpose of LinkedHashMap?
A: LinkedHashMap stores key-value pairs in the order they were inserted.