当前位置:网站首页>Getordefault method of map class

Getordefault method of map class

2022-06-30 08:03:00 Lafiteeee

Methods to introduce

java.util.Map<K, V>
public V getOrDefault(Object key, V defaultvalue)

If in map Key found in key The value of the match , Then return the value , Otherwise, return the default value defaultvalue.

================

Usage examples 1:

Array arr There may be duplicate elements in , Will array arr Record the number of occurrences of elements in .

int[] arr = new int[]{
    11, 22, 22, 44, 55};
Map<Integer, Integer> map = new HashMap<>();
for(int num : arr){
    
	int temp = map.getOrDefault(num, 0) + 1;
	map.put(num, temp);
}
System.out.println(map);
/*Out: <22, 2> <55, 1> <11, 1> <44, 1> */

Pay attention to the brief description when traversing the array for(int num : arr), there num It's every element in the array .

原网站

版权声明
本文为[Lafiteeee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160537472485.html