java中HashMap的使用方法以及遍历方式
方式一:利用迭代器
import java.util.*;
public class test {
public static void main(String[]args) {
Map map = new HashMap();
map.put("xly","123");
map.put("xhp","234");
map.put("swj","345");
map.put("zxy","456");
//注意这里用的是entrySet();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key);
System.out.println(value);
}
System.out.println(map);
}
}
输出结果:
xhp
234
xly
123
swj
345
zxy
456
{xhp=234, xly=123, swj=345, zxy=456}
***这是使用迭代器效率高的一种方式***
迭代器方式二:
import java.util.*;
public class test {
public static void main(String[]args) {
Map map = new HashMap();
map.put("xly","123");
map.put("xhp","234");
map.put("swj","345");
map.put("zxy","456");
//注意这里用的是keySet();
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()){
// Map.Entry entry = (Map.Entry) iterator.next();
Object key = iterator.next();
Object value = map.get(key);
System.out.println(key);
System.out.println(value);
}
// System.out.println(map);
}
}
输出结果:
xhp
234
xly
123
swj
345
zxy
456
***这是使用迭代器效率低一点的方式***
二:使用for each 遍历
import java.util.*;
public class test {
public static void main(String[]args) {
Map map = new HashMap();
map.put("xly","123");
map.put("xhp","234");
map.put("swj","345");
map.put("zxy","456");
for (Object key : map.keySet()){
Object value = map.get(key);
System.out.println(key);
System.out.println(value);
}
// System.out.println(map);
}
}
输出结果:
xhp
234
xly
123
swj
345
zxy
456