2

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

4
  • 1
    Yes, it is possible, why wouldn't it? Commented Jun 22, 2016 at 14:50
  • 1
    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. Commented Jun 22, 2016 at 14:50
  • 1
    public Map<Key, Value> getMyMagicMap(final Input input)? Commented Jun 22, 2016 at 14:50
  • 1
    Why would you think you can't do this? Have you tried doing it? Commented Jun 22, 2016 at 14:51

1 Answer 1

11

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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 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 -- if we are going to teach, we should encourage best practices. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.