search
HomeJavajavaTutorialHow to use HashMap function for mapping operations in Java

The HashMap function is a very commonly used mapping function in Java, which allows us to store and access data in the form of key-value pairs. This article will introduce how to use the HashMap function for mapping operations.

First of all, we need to understand what the HashMap function is. HashMap is a hash table data structure in Java that implements the Map interface. It allows us to store key-value pairs and retrieve the corresponding value by key. HashMap converts the key into an index through a hash function and stores the value at the location corresponding to the index. When we need to get a value, we use the key to calculate the index where the value is located, and find the corresponding value at the position of the index.

Next, let’s take a look at the specific usage of the HashMap function.

  1. Create a HashMap object

First, we need to create a HashMap object. You can create an empty HashMap object through the following code:

HashMap<K, V> map = new HashMap<K, V>();

where K and V represent the key and value types respectively. For example, if we want to store string type keys and integer type values, we can write:

HashMap<String, Integer> map = new HashMap<String, Integer>();
  1. Add key-value pairs

Next, we can use put Method to add key-value pairs to HashMap, the sample code is as follows:

map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);

This code will add three key-value pairs to HashMap, namely (key1, 1), (key2, 2) and (key3 , 3).

It is worth noting that if the key we add already exists in the HashMap, the put method will overwrite the value corresponding to the key. If we don't want to replace the existing key-value pair, we can use the putIfAbsent method. This method will only add a key-value pair when the key does not exist. The sample code is as follows:

map.putIfAbsent("key1", 4);

The above code will not change the key-value pair (key1, 1) because the key already exists in the HashMap.

  1. Get the key-value pair

Next, we can use the get method to get the value corresponding to the key from the HashMap. The sample code is as follows:

int value = map.get("key1");

This code will get the value with key "key1" and assign it to the value variable.

It should be noted that if we get the value of a key that does not exist, null will be returned.

  1. Traverse HashMap

You can use the for-each loop to traverse HashMap. The sample code is as follows:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + " -> " + value);
}

The above code traverses all key-value pairs in HashMap , and print their keys and values.

  1. Delete key-value pairs

Finally, we can use the remove method to delete the key-value pairs in the HashMap. The sample code is as follows:

map.remove("key1");

This code The key-value pair with key "key1" will be deleted. If the key does not exist, the remove method will have no effect.

Through the above steps, we can use the HashMap function to perform mapping operations. It is important to note that when using a HashMap, the keys need to be unique and immutable. Therefore, we need to make sure that the key type we use is an immutable type, such as a string, integer, or enumeration type.

The above is the detailed content of How to use HashMap function for mapping operations in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.