当前位置:网站首页>The Map Entry understanding and application
The Map Entry understanding and application
2022-07-31 03:04:00 【Lin Fanchen coding】
概述
Map.Entry是Map接口的一个内部接口,用于获取Mapelement key-value pair.可以通过map.entrySet()的返回值是一个Set,其类型为Map.Entry,常用的有以下几个方法:
- getKey():get the key of the element
- getValue():获取元素的值
- setValue():设置元素的值
实例
MapHow to traverse type data
package com.linfanchen.springboot.lab.map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapEntryTest {
@Test
public void carPriceTest() {
Map<String, Integer> carPriceMap = new HashMap<>();
carPriceMap.put("bmw", 500000);
carPriceMap.put("benz", 550000);
carPriceMap.put("lexus", 440000);
// 遍历方式一:使用Map.keySet()
for (String key : carPriceMap.keySet()) {
System.out.println("key=" + key + ", value=" + carPriceMap.get(key));
}
// 遍历方式二(推荐):使用Map.entrySet()的iterator()迭代器
Iterator<Map.Entry<String, Integer>> iterator = carPriceMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
// 遍历方式三(推荐):entrySet()
for (Map.Entry<String, Integer> entry : carPriceMap.entrySet()) {
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
// 遍历方式四:使用map.values()只能获取值
for (Integer val : carPriceMap.values()) {
System.out.println("value=" + val);
}
}
}
遍历效率
代码
写个Case验证一下:
package com.linfanchen.springboot.lab.map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapEntryTest {
@Test
public void carPriceTest() {
Map<String, Integer> carPriceMap = new HashMap<>();
carPriceMap.put("bmw", 500000);
carPriceMap.put("benz", 550000);
carPriceMap.put("lexus", 440000);
// 遍历方式一:使用Map.keySet()
for (String key : carPriceMap.keySet()) {
System.out.println("key=" + key + ", value=" + carPriceMap.get(key));
}
// 遍历方式二(推荐):使用Map.entrySet()的iterator()迭代器
Iterator<Map.Entry<String, Integer>> iterator = carPriceMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
// 遍历方式三(推荐):entrySet()
for (Map.Entry<String, Integer> entry : carPriceMap.entrySet()) {
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
// 遍历方式四:使用map.values()只能获取值
for (Integer val : carPriceMap.values()) {
System.out.println("value=" + val);
}
}
@Test
public void speedTest() {
{
// 构造500w的数据源
HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
for (int i = 0; i < 5000000; i++) {
hashmap.put(i, "lfc");
}
long bs = Calendar.getInstance().getTimeInMillis();
Iterator iterator = hashmap.keySet().iterator();
while (iterator.hasNext()) {
hashmap.get(iterator.next());
}
System.out.print("keyset:");
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
{
// 构造500w的数据源
HashMap<Integer,String> hashmap = new HashMap<Integer,String>();
for (int i = 0; i < 5000000; i++ ) {
hashmap.put(i, "lfc");
}
long bs = Calendar.getInstance().getTimeInMillis();
Iterator it = hashmap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
entry.getValue();
}
System.out.print("entryset:");
System.out.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}
}
输出:
keyset:120
entryset:98
从输出结果看出entrysetThe convenience and performance will be much better,那为什么呢?
Find the answer from the source code:
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
- hashmap.entryset:在set集合中存放的是entry对象.而在hashmap中的key 和 value 是存放在entry对象里面的;然后用迭代器,遍历set集合,you can get everyentry对象;得到entryobjects can be accessed directly fromentry拿到value了;
- hashmap.keyset:只是把hashmap中key放到一个set集合中去,Or through the iterator to traverse,然后再通过 hashmap.get(key)方法拿到value;
源码
位于 java.util.Map
:
public interface Entry<K, V> {
/* * 获取键 */
K getKey();
/* * 获取值 */
V getValue();
/* * 设置值 */
V setValue(V var1);
boolean equals(Object var1);
int hashCode();
/* * Compare by key,Specific comparative logic */
static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K, V>> comparingByKey() {
return (Comparator)((Serializable)((c1, c2) -> {
return ((Comparable)c1.getKey()).compareTo(c2.getKey());
}));
}
/* * Compare by value,Specific comparative logic */
static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K, V>> comparingByValue() {
return (Comparator)((Serializable)((c1, c2) -> {
return ((Comparable)c1.getValue()).compareTo(c2.getValue());
}));
}
/* * Compare by key,Specific comparative logic */
static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator)((Serializable)((c1, c2) -> {
return cmp.compare(c1.getKey(), c2.getKey());
}));
}
/* * Compare by value,Specific comparative logic */
static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator)((Serializable)((c1, c2) -> {
return cmp.compare(c1.getValue(), c2.getValue());
}));
}
}
总结
在日常的开发中,要注意mapType traversal efficiency.可以使用entrySet()高效遍历,Save program running time.PS:Why is Apple's operating system so smooth?,It is to optimize the efficiency of each line of code as much as possible,We have to follow the same philosophy.
边栏推荐
- [Godot][GDScript] 二维洞穴地图随机生成
- Clustering index, and what is the difference between a clustering index
- 原子操作 CAS
- 15、网站统计数据
- 11、Redis实现关注、取消关注以及关注和粉丝列表
- SQL注入 Less47(报错注入) 和Less49(时间盲注)
- Intel's software and hardware optimization empowers Neusoft to accelerate the arrival of the era of smart medical care
- 软件积累 -- 截图软件ScreenToGif
- Difference between CMOS and TTL?
- Thesis framework of the opening report
猜你喜欢
19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing
Why is String immutable?
Compile Hudi
【Android】Room —— SQLite的替代品
关于 mysql8.0数据库中主键位id,使用replace插入id为0时,实际id插入后自增导致数据重复插入 的解决方法
Mysql 45讲学习笔记(二十三)MYSQL怎么保证数据不丢
接口测试关键技术
华为分布式存储FusionStorage知识点总结【面试篇】
STM32问题合集
YOLOV5 study notes (2) - environment installation + operation + training
随机推荐
Why is String immutable?
【Cocos Creator 3.5】缓动系统停止所有动画
测试中的误报和漏报同样的值得反复修正
6. Display comments and replies
Moxa NPort 设备缺陷可能使关键基础设施遭受破坏性攻击
STM32问题合集
学习DAVID数据库(1)
Unity3D Button 鼠标悬浮进入与鼠标悬浮退出按钮事件
mycat的主从关系 垂直分库 水平分表 以及mycat分片联表查询的配置详解(mysql5.7系列)
CorelDRAW2022精简亚太新增功能详细介绍
【C语言】三子棋(经典解法+一览图)
原子操作 CAS
How to build a private yum source
[Godot][GDScript] 二维洞穴地图随机生成
MultipartFile file upload
【C语言】预处理操作
SQL 面试用题(重点)
Crypto Firms Offer Offer To Theft Hackers: Keep A Little, Give The Rest
Maximum area of solar panel od js
execsnoop tool