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

P b*_*sak 51 java collections linkedhashmap

我有以下LinkedHashMap声明.

LinkedHashMap<String, ArrayList<String>> test1
Run Code Online (Sandbox Code Playgroud)

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

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

String key = iterator.next().toString();  
ArrayList<String> value = (ArrayList<String> )test1.get(key)
Run Code Online (Sandbox Code Playgroud)

mat*_*t b 138

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

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

  • 为什么在entrySet返回集合时保证订单?我知道在LinkedHashMap中保证了顺序,但是文档说集合的迭代器不能保证顺序 (24认同)
  • 我不是说不使用`LinkedHashMap` - 但通常最好的做法是声明像`Map <String,List <String >> map = new LinkedHashMap <String,List <String >>`. (4认同)
  • 顺便说一下,我希望列表中包含插入顺序,我之前使用过hashmap但它搞砸了订单. (3认同)
  • @Jonathan.,好问题.迟到总比没有好:请参阅http://stackoverflow.com/a/2924143/423105上的答案 (3认同)
  • 为什么在声明中保留ArrayList呢? (2认同)

Eri*_* B. 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();
  // ...
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

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

在声明变量时(以及在通用参数中),您应该使用接口名称,除非您有一个非常具体的原因来定义使用该实现.


Mar*_*iot 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 从来没有想过这个,我在C#中使用了foreach,这与此类似. (2认同)

Kon*_*che 6

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

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

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

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


Jon*_*297 6

在Java 8中:

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