map遍历的几种方式举例
1.代码
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class MapBianLi {
public static void main(String[] args) {
out("map遍历");
MapBianLi mpbl = new MapBianLi();
mpbl.mian();
}
private static void out(String str) {
System.out.println(str);
}
Map <String,String>map = new HashMap<String,String>();
public void mian() {
map.put("key1", "value1");
map.put("key2", "value2");
bianLi1();
bianLi2();
bianLi3();
bianLi4();
}
private void bianLi1() {
//最常见也是大多数情况下用的最多的,一般在键值对都需要使用
out("\nmap遍历:1");
for(Map.Entry<String, String> entry : map.entrySet()){
String mapKey = entry.getKey();
String mapValue = entry.getValue();
out(mapKey+":"+mapValue);
}
}
private void bianLi2() {
//在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;
out("\nmap遍历:2");
//key
for(String key : map.keySet()){
out(key);
}
//value
for(String value : map.values()){
out(value);
}
}
private void bianLi3() {
//通过Iterator遍历;
out("\nmap遍历:3");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
}
private void bianLi4() {
//通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;
out("\nmap遍历:4");
for(String key : map.keySet()){
String value = map.get(key);
System.out.println(key+":"+value);
}
}
}
2.运行效果
map遍历
map遍历:1
key1:value1
key2:value2
map遍历:2
key1
key2
value1
value2
map遍历:3
key1:value1
key2:value2
map遍历:4
key1:value1
key2:value2