Is it possible to return a HashMap object in Java?

31,842

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?

Share:
31,842
user6437583
Author by

user6437583

Updated on June 23, 2020

Comments

  • user6437583
    user6437583 about 4 years

    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

    • tkausl
      tkausl about 8 years
      Yes, it is possible, why wouldn't it?
    • mdewit
      mdewit about 8 years
      Can you add some code to your question please? Then we will have a look to see if what you want to do is correct.
    • Boris the Spider
      Boris the Spider about 8 years
      public Map<Key, Value> getMyMagicMap(final Input input)?
    • azurefrog
      azurefrog about 8 years
      Why would you think you can't do this? Have you tried doing it?
  • Grayson
    Grayson about 8 years
    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.
  • Cache Staheli
    Cache Staheli about 8 years
    @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.
  • Grayson
    Grayson about 8 years
    @ Cache Staheli -- if we are going to teach, we should encourage best practices. ;-)