0

HashMap

what we can achieve using getOrDefault method ? This question arises so many times in my mind and i have searched a lot on google but unable to understand it properly. so please explain it to me ....! Map<Long, Integer> map = new HashMap<>(); for (long num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); }

6th Sep 2022, 5:45 AM
Davinder Kumar
Davinder Kumar - avatar
4 Réponses
+ 5
getOrDefault method returns provided default value if key doesn't match in Map. if num not exist in nums then 0 will be return
6th Sep 2022, 5:56 AM
A͢J
A͢J - avatar
+ 4
getOrDefault method have two param, - the Key searched, if exists return value of this key - default value, if Key searched don't be find return default value Exemple : HashMap<String, Integer> map = new HashMap<>(); map.put("a", 100); map.put("b", 200); map.put("c", 300); map.put("d", 400); int exOne = map.getOrDefault("b", 500); // exOne = 200 int exTwo = map.getOrDefault("y", 500); //.exTwo = 500
6th Sep 2022, 6:02 AM
Roland
Roland - avatar
+ 3
I thought you got it figured out ... https://www.sololearn.com/Discuss/3072359/?ref=app
6th Sep 2022, 8:30 AM
Ipang
+ 3
Ipang i forgot it 🙂
6th Sep 2022, 12:49 PM
Davinder Kumar
Davinder Kumar - avatar