- A+
所属分类:Java
写了几个关于map遍历的方法,然后接下来的四个小时里一直在折腾代码高亮插件,最终也没能解决,真是醉了,只好自定义了个标签,先凑合用用。
package net.circleblog.base;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* map的各种迭代方式
* 说明:HashMap、TreeMap、LinkedHashMap、HashTable都实现了Map接口,如下四种方法对这几个类型都适用
* @author liulei
* @time 2015-7-23 上午9:58:46
* @E-mail liulei@fun.tv
*/
public class MapIterator {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < 10; i++) {
map.put(i + "", "the value is " + i);
}
method1(map);
method2(map);
method3(map);
method4(map);
}
/**
* 方法一:利用entry来迭代
* 说明:这种事最常用和效率最高的
* 结果:
* key:3 value:the value is 3
* key:2 value:the value is 2
* key:1 value:the value is 1
* key:0 value:the value is 0
* key:7 value:the value is 7
* key:6 value:the value is 6
* key:5 value:the value is 5
* key:4 value:the value is 4
* key:9 value:the value is 9
* key:8 value:the value is 8
*/
public static void method1(Map<String, String> map){
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}
}
/**
* 方法二:使用iterator来迭代
* 结果:
* key:3values:the value is 3
* key:2values:the value is 2
* key:1values:the value is 1
* key:0values:the value is 0
* key:7values:the value is 7
* key:6values:the value is 6
* key:5values:the value is 5
* key:4values:the value is 4
* key:9values:the value is 9
* key:8values:the value is 8
*/
public static void method2(Map<String, String> map){
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
Entry<String, String> next = entries.next();
System.out.println("key:" + next.getKey() + "values:" + next.getValue());
}
}
/**
* 方法三:如果只是需要key 或者 vaule里的内容,可以分别迭代key 或者 value
* 结果:
* key:3
* key:2
* key:1
* 省略
* value:the value is 4
* value:the value is 9
* value:the value is 8
*/
public static void method3(Map<String, String> map){
//循环key
for (String str : map.keySet()) {
System.out.println("key:" + str);
}
//循环value
for (String str : map.values()) {
System.out.println("value:" + str);
}
}
/**
* 方法四:通过遍历key来获取对应的value
* 说明:这个方法可以认为是方法#1的缩减版,但是从实际来看,这种方法是非常慢和效率低下的,因为通过key来获取value是比较耗时的。(这种方法对不同的map实现会比第一种方法慢20%--200%)。
* 这个方法要尽量少用。
* 结果:
* key:3value:the value is 3
* key:2value:the value is 2
* 省略
* key:9value:the value is 9
* key:8value:the value is 8
*/
public static void method4(Map<String, String> map){
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("key:" + key + "value:" + value);
}
}
}