HashMap遍历方式包含以下4种:
1、遍历KeySet,再通过Key来getValue。
2、使用entrySet的迭代器。
3、foreach entrySet的方式。
3、foreache values的方式。
试例代码:
public class Demo {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
map.put("张三", new Double(10));
map.put("李四", new Double(1.5));
map.put("王五", new Double(2.2));
map.put("刘大能", new Double(5.0));
map.put("金三胖", new Double(30.0));
//HashMap遍历方式:1、使用KeySet
System.out.println("---------------1、使用keySet方式遍历------------");
for(String key:map.keySet()) {
System.out.println("Key:"+key+" value:"+map.get(key));
}
//HashMap遍历方式:2、使用iterator
System.out.println("---------------2、使用迭代器方式遍历------------");
Iterator ite = map.entrySet().iterator();
while(ite.hasNext()) {
Map.Entry<String, Double> entry = (Map.Entry<String, Double>)ite.next();
System.out.println("Key:"+entry.getKey()+" value:"+entry.getValue());
}
//HashMap遍历方式:3、使用entrySet遍历。 大数据量时建议使用
System.out.println("---------------3、使用entrySet遍历。 大数据量时建议使用------------");
for(Entry<String, Double> entry : map.entrySet()) {
System.out.println("Key:"+entry.getKey()+" value:"+entry.getValue());
}
//HashMap遍历方式:4、foreach values 方式
System.out.println("---------------4、foreach values 方式------------");
for(Double d :map.values()) {
System.out.println(d);
}
}
}