我有以下LinkedHashMap声明。
LinkedHashMap<String, ArrayList<String>> test1
我的观点是如何迭代这个哈希图。我想做以下操作,为每个键获取相应的arraylist,并针对该键逐个打印arraylist的值。
我试过了,但get只返回字符串,
String key = iterator.next().toString();
ArrayList<String> value = (ArrayList<String> )test1.get(key)
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>>
。
我假设你的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时(以及在泛型params中),您应该使用接口名称,除非您有非常具体的原因使用实现进行定义。
在Java 8:中
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
您可以使用条目集并迭代条目,这允许您直接访问键和值。
for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
我试过了,但只返回字符串
你为什么这么认为?方法get
返回为其选择泛型类型参数的类型E
,在本例中为ArrayList<String>
。
// 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);
}
}