1

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

user6437583
  • 75
  • 1
  • 1
  • 10

1 Answers1

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
  • 3
    Better 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