Java中遍历Map的几种方法
前言
java中的map遍历有多种方法,从最早的Iterator,到java5支持的foreach,再到java8 Lambda,让我们一起来看下具体的用法以及各自的优缺点
先初始化一个map
1
| public static Map<Integer,Integer> map = new HashMap<Integer, Integer>();
|
keySet values
如果只需要map的key或者value,用map的keySet或values方法无疑是最方便的
1 2 3 4 5 6 7 8 9 10 11 12 13
| private static void testKeyset(){ for(Integer key :map.keySet()){ System.out.println(key); } }
private static void testValue(){ for(Integer value :map.values()){ System.out.println(value); } }
|
keySet get(key)
如果需要同时获取key和value,可以先获取key,然后再通过map的get(key)获取value
需要说明的是,该方法不是最优选择,一般不推荐使用
1 2 3 4 5 6
| private static void testKeysetAndKey(){ for(Integer key :map.keySet()){ System.out.println(key+":"+map.get(key)); } }
|
entrySet
通过对map entrySet的遍历,也可以同时拿到key和value,一般情况下,性能上要优于上一种,这一种也是最常用的遍历方法
1 2 3 4 5 6
| private static void testEntry(){ for(Map.Entry<Integer,Integer> entry:map.entrySet()){ System.out.println(entry.getKey()+":"+entry.getValue()); } }
|
Iterator
对于上面的几种foreach都可以用Iterator代替,其实foreach在java5中才被支持,foreach的写法看起来更简洁
但Iterator也有其优势:在用foreach遍历map时,如果改变其大小,会报错,但如果只是删除元素,可以使用Iterator的remove方法删除元素
1 2 3 4 5 6 7 8 9
| private static void testIterator(){ Iterator<Map.Entry<Integer,Integer>> it = map.entrySet().iterator(); while (it.hasNext()){ Map.Entry<Integer,Integer> entry = it.next(); System.out.println(entry.getKey()+":"+entry.getValue()); it.remove(); } }
|
Lambda
java8提供了Lambda表达式支持,语法看起来更简洁,可以同时拿到key和value,不过,经测试,性能低于entrySet,所以更推荐用entrySet的方式
1 2 3 4 5 6
| private static void testLambda() { map.forEach((key, value) -> { System.out.println(key + ":" + value); }); }
|