【java笔记】java中的Map.Entry和Map.entrySet()方法的使用
Map.entrySet()方法返回的是一个Set<Map.Entry<K,V>>类型的值,首先该返回值是一个集合Set,集合中的元素是Map.Entry<K,V>类型的,每个Map.Entry可以看作是一个键值对对象,可以通过getKey()和getValue()方法分别获取其键和值。
Map.entrySet()方法主要用在对Map的键和值的遍历上,你可能会问了,既然已经有了更简便的方法去访问Map的键和值,为什么又要弄一个相对复杂的东西呢?答案就是速度更快,特别是在对大容量的Map进行键值对的遍历时。先看下面例子中的两种遍历方式。
package ecnu.cn; import java.util.HashMap; import java.util.Map; public class MyTest { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "value1"); map.put(2, "value2"); map.put(3, "value3"); map.put(4, "value4"); map.put(5, "value5"); for (Integer key : map.keySet()) { System.out.println("key: " + key + " value: " + map.get(key)); } System.out.println(); for(Map.Entry<Integer,String> entry:map.entrySet()){ System.out.println("key: "+entry.getKey()+" value: "+entry.getValue()); } } }
那为什么第一种常用的遍历方式会更慢呢?我的理解是:该种方式是先取出所有键的集合,然后拿着每个键再去Map中查找对应的值。而第二种方法是直接遍历每个键值对,直接用getKey()和getValue()方法分别获取其键和值即可。所以很明显第一种方式是多了一步的,也就更慢一些了。