java 迭代哈希图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14301455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over hashmap
提问by nithin
Possible Duplicate:
How do I iterate over each Entry in a Map?
How can I iterate over a map of <String, POJO>?
I've written the following piece of code and am stuck on iterating over the hashmap.
我写了下面的一段代码,并坚持迭代哈希图。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
class demo
{
public static void main(String v[]) {
ArrayList<String> contactIds = new ArrayList<String>();
contactIds.add("2");
contactIds.add("3");
HashMap names = new HashMap();
names = getNames(contactIds);
// I want to get the total size of the hashmap - names
// for ex now there are 6 elements inside hashmap.
// How can I get that count?
}
private static HashMap getNames(ArrayList contactIds) {
HashMap names = new HashMap();
String params = null;
List<String> list = new ArrayList<String>();
for(int i=0; i<contactIds.size();i++) {
params = contactIds.get(i).toString();
list.add(0,"aer-1");
list.add(1,"aer-2");
list.add(2,"aer-3");
names.put(params,list) ;
}
return names;
}
}
In this code, there are six elments inside the map, now in the main method how can I iterate over the map and get the total count?
在这段代码中,地图中有六个元素,现在在 main 方法中如何遍历地图并获得总数?
Thank you.
谢谢你。
回答by paulsm4
Your question is asked - and answered - here:
您的问题在这里被问到并得到回答:
How to efficiently iterate over each Entry in a Map?
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
回答by SimonC
回答by Dan
The 'Map' data structure isn't a Collection object but Sets are.
'Map' 数据结构不是 Collection 对象,但 Sets 是。
The most common method to iterate over a Map is using the underlying .entrySet method.
迭代 Map 的最常见方法是使用底层 .entrySet 方法。
// For each loop
for ( Entry<String, String> entry : names ) {
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}
// Iterator
Iterator iterator = names.entrySet().iterator
while( iterator.hasNext() ){
Entry entry = iterator.next()
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}
If are interested in finding the total number of Map nodes, use the .size() method.
如果对查找 Map 节点的总数感兴趣,请使用 .size() 方法。
EDIT:
编辑:
Since you want the total size of each list stored within the map, you could do something like this.
由于您希望将每个列表的总大小存储在地图中,因此您可以执行以下操作。
Iterator iterator = names.entrySet().iterator
int count = 0;
while( iterator.hasNext() ){
Entry entry = iterator.next()
count += entry.getValue().size()
}