How to make dynamic variable names in Java?

Let say we have the following array list of countries.

List countries = Arrays.asList("Finland", "Norway", "France", "Sweden", "Germany");

Now we want dynamic variable names to assign each of the countries like below:

country1 = "Finland";
country2 = "Norway";

Later we want to use those dynamic name variables. How can we do it in Java?

How to achieve that in Java?

Java handles this in a different way. There are no concepts of dynamic variables in Java. In Java, the variables have to be declared in the source code. We can easily use a Map to solve this issue.

int index = 1;
List countries = Arrays.asList("Finland", "Norway", "France", "Sweden", "Germany");
Map countryMap = new HashMap();
for(String item : countries){
    if(!Objects.isNull(item)){
        countryMap.put("country" + index++, item);
    }
}

Now we can get it using get method like below:

countryMap.get("country1"); // Finland
countryMap.get("country2"); // Norway

Reference

Share