您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“HashMap方法之Map.getOrDefault()怎么使用”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
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.
意思就是當(dāng)Map集合中有這個key時,就使用這個key值,如果沒有就使用默認(rèn)值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()怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。