There are two ways to achieve this. One of them is to make the populateMyMap method a static initializer (or the approach suggested by AH). Then execution is guaranteed before the first static call. This is usually the best way, assuming either the cost of running populateMyMap is small enough to not be noticed, or if you intend to use the functionality of this class almost every time the application starts.
An alternative approach is what you would use if running populateMyMap is something that takes a considerable amount of time. And either you cannot use the functionality for some executions of the application, or you want to delay the execution of populateMyMap until the data is needed, so as not to increase the launch time.
If the second approach is what you want, you should switch structures and use singleton, not static methods. Add non-static methods (and data) and each user of them will receive a Singleton instance before calling the method on it. Have the "populateMyMap" called in the (private) constructor. Yes, I know that singleton have a bad reputation and people always say “avoid them because they just mask global methods”, but static methods are also just global methods. You have nothing to lose. And in this way you do not pay the cost to execute populateMyMap until you need it (or if you need it).
A WARNING. If your data structures are not immutable, that is, they can be changed after they are initialized, then you probably should not use any of these structures.
source share