我正在将一些PHP代码移植到Java上。我有一个定义以下地图的类:
class Something {
protected $channels = array(
'a1' => array(
'path_key1' => 'provider_offices',
'path_key2' => 'provider_offices',
),
'a2' => array(
'path_key1' => 'provider_users',
'path_key2' => 'provider_users',
),
'a3' => array(
'path_key1' => 'provider_offices',
'path_key2' => 'provider_offices',
),
'a4' => array(
'path_key1' => 'attri1',
'path_key2' => 'attri1',
),
'a5' => array(
'path_key1' => 'attrib2',
'path_key2' => 'attrib2',
),
'a6' => array(
'path_key1' => 'diagnosis',
'path_key2' => 'diagnosis',
),
'a7' => array(
'path_key1' => 'meds',
'path_key2' => 'meds',
),
'a8' => array(
'path_key1' => 'risk1',
'path_key2' => 'risk1',
),
'a9' => array(
'path_key1' => 'risk2',
'path_key2' => 'risk2',
),
'a0' => array(
'path_key1' => 'visits',
'path_key2' => 'visits',
),
);
}
在PHP中,通过执行以下操作来访问数据:
$key = 'a9';
$pathKey2Value = $this->channels[$key]['path_key2'];
我开始在Java中实现Map<String, Map<String, String>>
成员,但它似乎过于复杂,以及定义A1
,A2
等类。
在Java中完成同样的事情最优雅的方法是什么?
答案 0 :(得分:1)
enum An {a1, a2, a3, a0}
class PathKeys {
String pathKey1;
String pathKey2;
PathKeys(String pathKey1, String pathKey2) {
this.pathKey1 = pathKey1;
this.pathKey2 = pathKey2;
}
}
Map<An, PathKeys> channels = new EnumMap<>(An.class);
void put(An an, PathKeys pk) {
channels.put(an, pk);
}
put(An.valueOf("a1"), new PathKeys("provider_offices", "provider_offices"));
String s = channels.get(An.a1).pathKey1;
从Perl,JSON,简单的PHP转换为类似Java的类型语言应该使用足够的数据结构和类型信息。之后更容易减少限制,但暂时有助于发现业务逻辑中的错误。因此,为最后一个保存Map + String一般化。
答案 1 :(得分:0)
答案 2 :(得分:0)
这样做的伎俩:
Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
private HashMap<String, String> loadMap(String[] str){
HashMap<String, String> map = new HashMap<String, String>();
map.put(str[0], str[1]);
map.put(str[2], str[3]);
return map;
}
map.put("a1", loadMap(new String[]{"path_key1", "provider_offices", "path_key2", "provider_offices"}));
map.put("a2", loadMap(new String[]{"path_key1", "attri1", "path_key2", "attri1"}));