LinkedHashMap類的getOrDefault()方法 (LinkedHashMap Class getOrDefault() method)
getOrDefault() method is available in java.util package.
getOrDefault()方法在java.util包中可用。
getOrDefault() method is used to get the value associated with the given key element when it exists otherwise it gets the default value for the given key element when no previous value associated with the given key.
getOrDefault()方法用于獲取與給定鍵元素關聯的值(如果存在),否則,當沒有先前與給定鍵關聯的值時,它將獲取給定鍵元素的默認值。
getOrDefault() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
getOrDefault()方法是一個非靜態方法,只能由類對象訪問,如果嘗試使用類名訪問該方法,則會收到錯誤消息。
getOrDefault() method does not throw an exception at the time of getting the value element.
getOrDefault()方法在獲取value元素時不會引發異常。
Syntax:
句法:
public getOrDefault(Object key_ele, Value def_val);
Parameter(s):
參數:
Object key_ele – represents the key element (key_ele) to which the associated value is to be retrieved.
對象key_ele –表示要將關聯值檢索到的鍵元素(key_ele)。
Value def_val – represents the default value (def_val) is to be retrieved when no previous value exist for the given key element.
值def_val –表示在給定鍵元素沒有先前值的情況下將檢索默認值(def_val)。
Return value:
返回值:
The return type of the method is Value, it returns the linked value for the given key element if exists otherwise it returns the default value (def_val).
該方法的返回類型為Value ,如果存在則返回給定鍵元素的鏈接值,否則返回默認值(def_val)。
Example:
例:
// Java program to demonstrate the example
// of getOrDefault(Object key_ele, Value def_val)
// method of LinkedHashMap
import java.util.*;
public class GetOrDefaultOfLinkedHashMap {
public static void main(String[] args) {
// Instantiates a LinkedHashMap object
Map < Integer, String > map = new LinkedHashMap < Integer, String > ();
// By using put() method is to add
// key-value pairs in a LinkedHashMap
map.put(10, "C");
map.put(20, "C++");
map.put(50, "JAVA");
map.put(40, "PHP");
map.put(30, "SFDC");
// Display LinkedHashMap
System.out.println("LinkedHashMap: " + map);
// By using getOrDefault() method is to
// return the value associated for the
// given key element if exists otherwise
// it returns the default value
Object val_ele = map.getOrDefault(50, "Microservices");
//Display val_ele
System.out.print("map.getOrDefault(50,Microservices): ");
System.out.println(val_ele);
}
}
Output
輸出量
LinkedHashMap: {10=C, 20=C++, 50=JAVA, 40=PHP, 30=SFDC}
map.getOrDefault(50,Microservices): JAVA
翻譯自: https://www.includehelp.com/java/linkedhashmap-getordefault-method-with-example.aspx