如何使用列表作为值迭代LinkedHashMap

时间:2012-09-07 02:24:52

标签: java collections linkedhashmap

我有以下LinkedHashMap声明。

LinkedHashMap<String, ArrayList<String>> test1

我的观点是如何迭代这个哈希映射。 我想这样做,为每个键获取相应的arraylist并逐个打印arraylist的值。

我试过了,但 get 只返回字符串

String key = iterator.next().toString();  
ArrayList<String> value = (ArrayList<String> )test1.get(key)

5 个答案:

答案 0 :(得分:131)

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

顺便说一句,您应该将变量声明为接口类型,例如Map<String, List<String>>

答案 1 :(得分:14)

我假设你的get语句中有一个拼写错误,它应该是test1.get(key)。如果是这样,我不确定为什么它不会返回一个ArrayList,除非你没有在地图中输入正确的类型。

这应该有效:

// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());

// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
  String key = entry.getKey();
  List<String>value = entry.getValue();
  // ...
}

或者您可以使用

// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
  List<String>value = test1.get(key);
  // ...
}

在声明你的vars(以及你的通用参数)时,你应该使用接口名称,除非你有一个非常具体的理由说明你使用该实现进行定义。

答案 2 :(得分:7)

// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}

答案 3 :(得分:6)

您可以使用条目集并遍历条目,这些条目允许您直接访问密钥和值。

for (Entry<String, ArrayList<String>> entry : test1.entrySet() {
     System.out.println(entry.getKey() + "/" + entry.getValue());
}
  

我试过这个,但只得到返回字符串

你为什么这么认为?方法get返回选择了泛型类型参数的E类型,在您的情况下为ArrayList<String>

答案 4 :(得分:6)

在Java 8中:

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});