创建一个map,其中value将再次成为java中的map类型

时间:2015-06-18 15:11:13

标签: java dictionary

我有一个地图,其中键是值列表并匹配到一个值,如下所示基本上我想创建一个地图,其中值将再次为地图类型

Deaswe = DealDate
TradeRe = TradeRef
Deadery = DealDate
Dealdt = DealDate
Traes = TradeRef
TraRef = TradeRef
Daelet = DealDate
TF = TradeRef

下面是实现该目的的代码

Map<String, List<String>> dataMap = new HashMap<String, List<String>>();
        dataMap.put ("TradeRef", Arrays.asList("TradeRe", "TraRef", "TF", "Traes"));
        dataMap.put ("DealDate", Arrays.asList("Dealdt", "Daelet", "Deadery", "Deaswe"));


        Map<String, String> itemMap = new HashMap<String, String>(); //New map for item->key mapping
        for(String key: dataMap.keySet()) //Get all keys and iterate through
            for(String item: dataMap.get(key)) //For each item in your value list
                itemMap.put(item, key); //Create new mapping item->key

现在上面的地图工作得很好但是我又想再创建一个地图,如下图所示,请告知我如何创建一个地图,其中的值将是我上面现有地图的类型

key     value 

B1      HashMap<String, List<String>>   

所以就像

B1  -->    Deaswe   --> DealDate
B2 --->    Dealdt   --> DealDate
B1  --->   TradeRe  --> TradeRef
B2  --->   Traes    -->  TradeRef
    folks please advise

2 个答案:

答案 0 :(得分:0)

您可以拥有字符串(键)和地图(值)

的地图

例如

Map<String, Map<String, String>> dataMap = new HashMap<String, HashMap<String, String>>();
Map<String, String> itemMap = new HashMap<String, String>();
item="some value";
key="some value";
itemMap.put(item, key);
dataMap.put("TradeRef",itemMap);

这只是一个例子。我在数据地图中使用了itemmap。您可以使用多个级别的地图,并将其作为每个级别的地图中的值插入。

您还可以参考此问题Map of maps - how to keep the inner maps as maps?和此链接http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

答案 1 :(得分:0)

您可以创建包含列表的地图地图:

Map<String, Map<String, List<String>>> mapOfMapOfStrings =
        new HashMap<String, Map<String, List<String>>>();
HashMap<String, List<String>> b1Map = new HashMap<String, List<String>>();
mapOfMapOfStrings.put("B1", b1Map);

HashMap<String, List<String>> b2Map = new HashMap<String, List<String>>();
mapOfMapOfStrings.put("B2", b2Map);

ArrayList<String> dealDateList = new ArrayList<String>();
ArrayList<String> tradeRefList = new ArrayList<String>();

b1Map.put("Deaswe", dealDateList);
b2Map.put("Dealdt", dealDateList);
b1Map.put("TradeRe", tradeRefList);
b2Map.put("Traes", tradeRefList);

dealDateList.add("DealDate1");
dealDateList.add("DealDate2");
tradeRefList.add("tradeRef1");
tradeRefList.add("tradeRef2");