Java中map.getOrDefault()方法的使用

Java中map.getOrDefault()方法的使用

Map.getOrDefault(Object key, V defaultValue)方法的作用是:
  當Map集合中有這個key時,就使用這個key值;
  如果沒有就使用默認值defaultValue。

代碼示例如下:

	HashMap<String, String> map = new HashMap<>();
	map.put("name", "cookie");
	map.put("age", "18");
	map.put("sex", "女");
	String name = map.getOrDefault("name", "random");
	System.out.println(name);// cookie,map中存在name,獲得name對應的value
	int score = map.getOrDefault("score", 80);
	System.out.println(score);// 80,map中不存在score,使用默認值80
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章