java hashmap 详解(你知道哪种方式效率最高吗)
java hashmap 详解(你知道哪种方式效率最高吗)for (Integer key : hashMap.keySet()) { System.out.println("key= " key " and value= " hashMap.get(key)); }第四种遍历方式采用Map.values()遍历所有的value,但不能遍历key第三种遍历方式采用Map.keySet遍历key和value:第一种遍历方式采用Map.entrySet遍历key和valuefor (Map.Entry<Integer String> entry : hashMap.entrySet()) { System.out.println("Key = " entry.getKey() " Value = " entry.getValue()
在Java语言中hashmap是我们最常用的数据结构,开发中经常会遇到遍历HashMap的时候,HashMap的遍历有多种方式,你知道哪种方式的效率最高吗?今天带大家一起来了解下。
Java
我们总共采用六种方式来遍历HashMap,计算效率的方式采用执行遍历之前记下时间,遍历之后记下结束时间,时间差就是遍历所用的时间。之后比较六种方式的时间的大小,时间差值越小代表效率越高。
private static HashMap<integer String> hashMap;static {
hashMap = new HashMap<>(); for (int i = 0; i < 10000; i ) {
hashMap.put(i "hello world");
}
}
首先创建一个HashMap,里面放入10000个键值对,接着我们来看下六种遍历方式
第一种遍历方式采用Map.entrySet遍历key和value
for (Map.Entry<Integer String> entry : hashMap.entrySet()) {
System.out.println("Key = " entry.getKey() " Value = " entry.getValue());
}
第二种遍历方式采用Map.entrySet使用Iterator遍历key和value
Iterator<Map.Entry<Integer String>> it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer String> entry = it.next();
System.out.println("key= " entry.getKey() " and value= " entry.getValue());
}
Java
第三种遍历方式采用Map.keySet遍历key和value:
for (Integer key : hashMap.keySet()) {
System.out.println("key= " key " and value= " hashMap.get(key));
}
第四种遍历方式采用Map.values()遍历所有的value,但不能遍历key
for (String v : hashMap.values()) {
System.out.println("value= " v);
}
第五种遍历方式采用Java 8 lambda表达式遍历
hashMap.forEach((k v) -> System.out.println("key: " k " value:" v));
第六种遍历方式采用Map.keySet遍历key和value:
Iterator it1 = hashMap.keySet().iterator();
while (it1.hasNext()) {
Integer integer= (Integer) it1.next();
System.out.println("key= " integer " and value= " hashMap.get(integer));
}
运行之后结果如下:
[97 45 51 39 112 45]
分别代表六种方式运行的时间,可以看到第四种遍历方式运行最快,但是它只能遍历value,所以如果同时遍历键值对,建议采用第二种或者第六种方式。
下面是最效率最高的遍历方式,采用Map.entrySet使用iterator遍历key和value
Iterator<Map.Entry<Integer String>> it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer String> entry = it.next();
System.out.println("key= " entry.getKey() " and value= " entry.getValue());
}
今天就介绍到这里!需要源码的同学可以关注我后台私信"hashmap",会自动把下载链接发给大家。
大家好!我是黑客之家小编,黑客之家头条号
分享黑客技术,物联网、GO、Python、Kotlin、Android、Java编程知识,科技资讯等
喜欢的朋友可以关注我的头条号!