在 Java 中定义 Map<String、Map<String、String>> map 的最佳方法是什么?


What would be the best way to define a Map<String, Map<String, String>> map in Java?

我正在将一些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>>成员,但它似乎过于复杂,以及定义A1A2等类。

在 Java 中完成同样事情的最优雅方法是什么?

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;
  • 枚举是类型安全的。
  • EnumMap 实际上是一个数组。
  • 我不确定路径键,但它看起来像自己结构的固定字段。

从Perl,JSON,简单的PHP翻译成像Java这样的类型语言应该使用足够的数据结构和类型信息。之后更容易减少限制,但暂时有助于查找业务逻辑中的错误。因此,将映射+字符串泛化留到最后。

如果可以包含第三方库,则添加 Guava 并使用 Table <</p>

div class="answers">

这样做可以做到技巧:

 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"}));