您好,登錄后才能下訂單哦!
本篇內容介紹了“HashMap方法之Map.getOrDefault()怎么使用”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
HashMap getOrDefault(key, defaultValue) method in Java with Examples
The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned.
Syntax:
default V getOrDefault(Object key, V defaultValue)
Parameters: This method accepts two parameters:
key: which is the key of the element whose value has to be obtained.
defaultValue: which is the default value that has to be returned, if no value is mapped with the specified key.
Return Value: This method returns value mapped with the specified key, otherwise default value is returned.
意思就是當Map集合中有這個key時,就使用這個key值,如果沒有就使用默認值defaultValue
Program 1:
// Java program to demonstrate // getOrDefault(Object key, V defaultValue) method import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put("a", 100); map.put("b", 200); map.put("c", 300); map.put("d", 400); // print map details System.out.println("HashMap: " + map.toString()); // provide key whose value has to be obtained // and default value for the key. Store the // return value in k int k = map.getOrDefault("b", 500); // print the value of k returned by // getOrDefault(Object key, V defaultValue) method System.out.println("Returned Value: " + k); } }
Output:
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 200
Program 2:
// Java program to demonstrate // getOrDefault(Object key, V defaultValue) method import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a HashMap and add some values HashMap<String, Integer> map = new HashMap<>(); map.put("a", 100); map.put("b", 200); map.put("c", 300); map.put("d", 400); // print map details System.out.println("HashMap: " + map.toString()); // provide key whose value has to be obtained // and default value for the key. Store the // return value in k int k = map.getOrDefault("y", 500); // print the value of k returned by // getOrDefault(Object key, V defaultValue) method System.out.println("Returned Value: " + k); } }
Output:
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 500
“HashMap方法之Map.getOrDefault()怎么使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。