Is it possible to return a HashMap object in Java?

We Are Going To Discuss About Is it possible to return a HashMap object in Java?. So lets Start this Java Article.

Is it possible to return a HashMap object in Java?

Advertisements
  1. Is it possible to return a HashMap object in Java?

    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; }

  2. Is it possible to return a HashMap object in Java?

    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; }

Solution 1

Advertisements

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?

Original Author Cache Staheli Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Advertisements
Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment