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>>.
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)
在声明变量时(以及在通用参数中),您应该使用接口名称,除非您有一个非常具体的原因来定义使用该实现.
// 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)
您可以使用条目集并遍历条目,这些条目允许您直接访问密钥和值.
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>.
在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)
| 归档时间: |
|
| 查看次数: |
131861 次 |
| 最近记录: |