This might be a silly question, but I have never found a satisfying way to name a variable of type HashMap<K,V> in Java. For example - lets say I have a HashMap where every bucket is a <K,V> pair where K is a String say representing "State" and V is an Integer representing the number of counties the state has.
Should the HashMap be named as "mapStateCounty", "stateToCountyMap", etc. ? Which one seems logically more appealing and intuitive to understand without sounding confusing and verbose?
To get a specific element stored in a Java Map you call its get() method, passing along the key for that element as parameter. Here is an example of getting a value stored in a Java Map : Map map = new HashMap(); map. put("key1", "value 1"); String element1 = (String) map.
I don't believe there is a hard-written rule anywhere that tells you how to name your map, so as long as you come up with a rule that makes sense to you (and your teammates), then it should be fine.
Personally, I like to call my maps keyToValue or valueByKey.
I like this question because Java does not allow map access via an operator like []. In other languages we could say things like
numberOfCountiesIn["HI"] or
countyCountOf["CA"] or
numCountiesIn->{"MA"} or (in Scala, this is cool)
numCountiesIn("WA") and on and on. None of these work in Java, because of that silly get word!
countyCounts.get("NY") Indeed!
EDIT: I actually think countyCounts is the best answer (IMHO); I was just making the point that the need for get limits one's choices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With