Home >Java >javaTutorial >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:
//创建一个HashMap对象 HashMap<String, Integer> myHashMap = new HashMap<>(); //向HashMap对象中添加元素 myHashMap.put("apple", 5); myHashMap.put("banana", 3); myHashMap.put("orange", 4); myHashMap.put("grape", 2);
//获取Key为"apple"的Value值 int appleNum = myHashMap.get("apple"); //获取Key为"banana"的Value值 int bananaNum = myHashMap.get("banana");
//检查键"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.
//获取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!