How do I build a HashMap in one class and then use it in another in Java?

Basically all I want to do is create a HashMap object in one class, build it in that class using a loop, and then be able to call it into another class. I’m not sure what I need to do to accomplish this. I tried declaring it in the class itself and then building it in the main() function, but that doesn’t allow me to access it outside of the class because it would need to be static.

Here is some psuedocode of what my thought process is:

public class Class1 {
    public Map<> map = new HashMap<>();

    public static void main(String[] args) {
    //build hashmap here using map.put etc

public class Class2 {
    public static void main(String[] args) {
    //get the map using


Update: I ended up just building and returning the hashmap in one method in Class1, then creating an instance of Class1 in Class2 and calling the method to return the hashmap

This was a rather simple solution, not sure why it was so difficult to find the answer. Thanks to everyone who tried to help

Leave a Reply

Your email address will not be published. Required fields are marked *