【问题标题】:Initialize and fill up a Map of Maps [duplicate]初始化并填充地图 [重复]
【发布时间】:2021-10-13 01:23:48
【问题描述】:

我有这样的数据 {"Atr1":{"col":1,"row":1}, "Atr2":{"col":1,"row":2}, ...}。列和行总是固定的,所以我想在 java 中创建最终属性。
如何初始化 Map> 和值。

我试过下面的代码,有没有更好的方法?

private final Map<String, HashMap<String, Integer>> FIELD_TO_INDEX = new HashMap<String, HashMap<String, Integer>>() {
        private static final long serialVersionUID = 1L;
        {
            put("Atr1",
                    new HashMap<String,Integer>(){
                        private static final long serialVersionUID = 1L;
                        {
                            put("col",1);
                            put("row",1);
                        }
                    }
            );
            put("Atr2",
                    new HashMap<String,Integer>(){
                private static final long serialVersionUID = 1L;
                {
                    put("col",1);
                    put("row",2);
                }
            }
                    );
            put("Atr3",
                    new HashMap<String,Integer>(){
                private static final long serialVersionUID = 1L;
                {
                    put("col",1);
                    put("row",3);
                }
            }
                    );
        

}
    };
 

【问题讨论】:

  • 像这样使用双括号初始化是一种反模式。

标签: java


【解决方案1】:

如果你不介意它是不可变的,也许

Map<String, Map<String, Integer>> outer = Map.of(
    "Map1", Map.of(
        "InnerMap1", 1,
        "InnerMap2", 2
        )
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2019-05-08
    相关资源
    最近更新 更多