Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a HashMap in Java?

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?

like image 246
user396089 Avatar asked Jul 12 '11 04:07

user396089


People also ask

How do you call a map in Java?

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.


2 Answers

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.

like image 184
RAY Avatar answered Oct 05 '22 05:10

RAY


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.

like image 30
Ray Toal Avatar answered Oct 05 '22 05:10

Ray Toal