Alexander Rumanovsk
Alexander Rumanovsk

Reputation: 2303

Retrieving variables with the same name as a string

I have a bunch of maps inside a class and I would like to make a generic method to retreive the specific map that matches the ID. Something like:

private Map map1;
private Map map2;
private Map map3;


public Map getMap(String id){
  return mapX;
}

And when I call the method as:

getMap("map1");

It will return map1. Any way I can do this conversion whithout creating a map of maps?

Upvotes: 0

Views: 108

Answers (4)

sForSujit
sForSujit

Reputation: 985

Map of map can be also the solution for this :

Map<String, Map<String, String>> map = new HashMap<>();

    map.put("map1", map1); 
    map.put("map2", map2);

public static Map<String, String> getMap(String name){
   return map.get(name);
}

Upvotes: 2

Vadim Beskrovnov
Vadim Beskrovnov

Reputation: 961

Try to use reflection, for example:

    private Map getMap(String id) throws NoSuchFieldException, IllegalAccessException {
        getClass().getField("map" + id).get(this);
        return map;
    }

Upvotes: 2

Amit
Amit

Reputation: 32376

If you are having only few numbers of map then you can use the switch statement and retuen the map which matches the map name like below code :-

switch (mapName) {
            case "map1":
                return map1;
            break;
            case "map2":
                return map2;
            break;
        }

But if you have large number of Maps then its better to give some id or name to them and use Map of Map.

Upvotes: 0

define a Map of String, Map and use it as dictionary

like:

private Map map1;
private Map map2;
private Map map3;
private Map<String, Map> mapX;

public Map getMap(String id) {
    return this.mapX.getOrDefault(id, null);
}

Upvotes: 0

Related Questions