Home  >  Article  >  Java  >  How to use HashMap.get() method in Java to get the value in the map?

How to use HashMap.get() method in Java to get the value in the map?

WBOY
WBOYOriginal
2023-11-18 09:37:48616browse

How to use HashMap.get() method in Java to get the value in the map?

HashMap is one of the commonly used collection classes in Java. It is used to store a set of Key-Value mapping relationships and is often used to quickly find and read data.

The get() method of HashMap is one of the most basic methods. This method can return the corresponding Value value through the given Key value. The following are the specific steps and sample code on how to use the HashMap.get() method to obtain the values ​​in the map:

  1. First, we need to create a HashMap object and add some elements to it (Key-Value key-value pairs).
//创建一个HashMap对象
HashMap<String, Integer> myHashMap = new HashMap<>();

//向HashMap对象中添加元素
myHashMap.put("apple", 5);
myHashMap.put("banana", 3);
myHashMap.put("orange", 4);
myHashMap.put("grape", 2);
  1. Next, we can use the get() method to obtain the Value corresponding to a Key.
//获取Key为"apple"的Value值
int appleNum = myHashMap.get("apple");

//获取Key为"banana"的Value值
int bananaNum = myHashMap.get("banana");
  1. We can also use the containsKey() method to check whether a certain Key value exists in a HashMap object.
//检查键"orange"是否存在于HashMap中
if(myHashMap.containsKey("orange")){
    //若存在,输出Value值
    System.out.println("Orange Num: " + myHashMap.get("orange"));
}

At this time, we can see on the console that the output result is "Orange Num: 4", which is the Value value corresponding to "orange" in the HashMap.

  1. If a Key value does not exist in the HashMap, the get() method will return a null value.
//获取Key为"watermelon"的Value值
Integer watermelonNum = myHashMap.get("watermelon");

if(watermelonNum == null){
    //若不存在,则输出提示语句
    System.out.println("No watermelon found in the HashMap");
}

At this time, we can see on the console that the output result is "No watermelon found in the HashMap", that is, the Value value corresponding to "watermelon" does not exist in the HashMap.

Through the above sample code, we can see the steps of using the HashMap.get() method and it is simple and easy to understand. In actual development, we can use it to quickly obtain the Value corresponding to the specified Key in the HashMap, thereby improving the efficiency of data reading.

The above is the detailed content of How to use HashMap.get() method in Java to get the value in the map?. 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