I have a method that maps keywords to a certain value. I want to return the actual hashmap so I can reference its key/value pairs
Asked
Active
Viewed 4.6k times
1
-
1Yes, it is possible, why wouldn't it? – tkausl Jun 22 '16 at 14:50
-
1Can you add some code to your question please? Then we will have a look to see if what you want to do is correct. – mdewit Jun 22 '16 at 14:50
-
1`public Map
getMyMagicMap(final Input input)`? – Boris the Spider Jun 22 '16 at 14:50 -
1Why would you think you can't do this? Have you tried doing it? – azurefrog Jun 22 '16 at 14:51
1 Answers
9
Yes. It is easily possible, just like returning any other object:
public Map<String, String> mapTheThings(String keyWord, String certainValue)
{
Map<String, String> theThings = new HashMap<>();
//do things to get the Map built
theThings.put(keyWord, certainValue); //or something similar
return theThings;
}
Elsewhere,
Map<String, String> actualHashMap = mapTheThings("keyWord", "certainValue");
String value = actualHashMap.get("keyWord"); //The map has this entry in it that you 'put' into it inside of the other method.
Note, you should prefer to make the return type Map
instead of HashMap
, as I did above, because it's considered a best practice to always program to an interface rather than a concrete class. Who's to say that in the future you aren't going to want a TreeMap
or something else entirely?

Community
- 1
- 1

Cache Staheli
- 3,510
- 7
- 32
- 51
-
3Better to make return type the interface Map. This is done so that if the implementation changes from HashMap to TreeMap, for example, the calling code does not necessarily have to be changed. – Grayson Jun 22 '16 at 14:54
-
@Grayson Good point. That's what I would have done, the OP just asked for `HashMap`. However, I changed it, because that is my sentiment as well. – Cache Staheli Jun 22 '16 at 14:55
-
3@ Cache Staheli -- if we are going to teach, we should encourage best practices. ;-) – Grayson Jun 22 '16 at 14:59