Home > Java > javaTutorial > body text

How to use map in java

下次还敢
Release: 2024-04-27 00:00:31
Original
1054 people have browsed it

Map is an interface that represents a collection of key-value pairs in Java and is used to store and search data efficiently. Its main uses include: storing data where each key corresponds to a unique value. Create unordered (HashMap), ordered (TreeMap), ordered and retain insertion order (LinkedHashMap) Maps. Add key-value pairs through the put() method, and obtain values ​​through the get() method. Traverse the Map using key sets (keySet()) and value sets (values()). Use the remove() method to delete key-value pairs.

How to use map in java

Usage of Map in Java

What is Map?

Map is an interface in Java, which represents a collection of key-value pairs. The key is used to uniquely identify each value, while the value can be any object.

Purpose:

Map is mainly used to store data, where each key corresponds to a unique value. This makes finding data, updating data, and deleting data very efficient.

Create Map:

You can use the following methods to create a Map:

  • HashMap: unordered and duplicates allowed key.
  • TreeMap: Ordered and does not allow duplicate keys.
  • LinkedHashMap: Ordered and allows duplicate keys, but preserves the order in which elements were inserted.

Add key-value pairs:

To add key-value pairs to the Map, you can use the put(key, value) method . If the key already exists, the existing value will be overwritten.

Get the value:

The value associated with a given key can be obtained using the get(key) method. If the key does not exist, returns null.

Traverse the Map:

You can use the keySet() and values() methods to traverse the keys and values ​​in the Map .

Delete key-value pairs:

You can use the remove() method to delete key-value pairs associated with a given key.

Example:

The following is a sample code that uses HashMap to create and use Map:

<code class="java">Map<String, Integer> ages = new HashMap<>();

ages.put("John", 30);
ages.put("Mary", 25);

System.out.println(ages.get("John")); // 输出:30

for (String key : ages.keySet()) {
    System.out.println(key + ": " + ages.get(key));
}</code>
Copy after login

The above is the detailed content of How to use map in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!