I don't understand This line. | Sololearn: Learn to code for FREE!


I don't understand This line.

I'm talking about this line 👇 map.put(n, map.getOrDefault(n,0)+1); Here is code 👇 https://code.sololearn.com/cW5prlf2F16c/?ref=app

8/13/2022 6:02:00 AM

Davinder Kumar

8 Answers

New Answer


Put a new item in <map> where <n> will act as item key getOrDefault() here is used to try finding an existing item having <n> as its key. When an item having <n> as key was already there, getOrDefault() returns the existing item's value. When such item cannot be found, getOrDefault() returns a default - the 0 (zero) supplied as the second argument in the getOrDefault() call. So when a map item having <n> as key already exist, we'll get item value, otherwise a zero. Either way, the value we get from getOrDefault() will be added by one. This effectively does frequency counting. When item exists, we get item's value + 1. When item doesn't exist, we get 0 (default value) + 1. When item exists, its value will be updated, otherwise a new item will be created with 1 as its value.


Just for training: Given a list of words and build a hashmap with key: a letter, value: A list of all words beginning with this letter.


It is a little hack... applied in many languages. The usecase is for hashmaps which eg are counting something or build a list as value. Normally you would initialize each key with 0 / empty list. But if you dont know that keys... in this case because you iterate the list only once.. it is the short form for - search key in hashmap - if value found use value, otherwise set value to 0 / empty list - add 1 /append item This little hack is definitely worth to be understood and spend some time on it.


From https://www.geeksforgeeks.org/hashmap-getordefaultkey-defaultvalue-method-in-java-with-examples/ "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."


Davinder Kumar I believe you're smarter and better than I am at this. I'll try my best... map.put(n, map.getOrDefault(n,0)+1); As I understand it, you are telling the program to look for "n" and if there is a problem, then you define a default for that position in the map, so the code can keep going.


Thanks you Oma Falk and Ausgrindtube for making me understand this.


Ausgrindtube I know the working of this method but here that line is confusing and I have already read the article on gfg. I just need to understand that line so pls explain that line separately 👀