当前位置:网站首页>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.
边栏推荐
- 选好冒烟测试用例,为进入QA的制品包把好第一道关
- 什么是系统?
- 关于 mysql8.0数据库中主键位id,使用replace插入id为0时,实际id插入后自增导致数据重复插入 的解决方法
- Classic linked list OJ strong training problem - fast and slow double pointer efficient solution
- Why is String immutable?
- Maximum area of solar panel od js
- 测试中的误报和漏报同样的值得反复修正
- Crypto Firms Offer Offer To Theft Hackers: Keep A Little, Give The Rest
- 2022牛客多校联赛第四场 题解
- The use of font compression artifact font-spider
猜你喜欢
YOLOV5 study notes (3) - detailed explanation of network module
【异常】The field file exceeds its maximum permitted size of 1048576 bytes.
4、敏感词过滤(前缀树)
MultipartFile file upload
7年经验,功能测试工程师该如何一步步提升自己的能力呢?
6. Display comments and replies
10、Redis实现点赞(Set)和获取总点赞数
Office automation case: how to automatically generate period data?
软件积累 -- 截图软件ScreenToGif
LeetCode简单题之找到和最大的长度为 K 的子序列
随机推荐
Modbus on AT32 MCU
原子操作 CAS
YOLOV5 study notes (2) - environment installation + operation + training
JS function this context runtime syntax parentheses array IIFE timer delay self.backup context call apply
JS 函数 this上下文 运行时点语法 圆括号 数组 IIFE 定时器 延时器 self.备份上下文 call apply
跨专业考研难度大?“上岸”成功率低?这份实用攻略请收下!
CentOS7下mysql5.7.37的安装【完美方案】
Addition and Subtraction of Scores in LeetCode Medium Questions
遗留系统的自动化策略
Detailed explanation of TCP (3)
编译Hudi
4. Sensitive word filtering (prefix tree)
Word/Excel fixed table size, when filling in the content, the table does not change with the cell content
【CocosCreator 3.5】CocosCreator 获取网络状态
【HCIP】ISIS
Mysql 45讲学习笔记(二十五)MYSQL保证高可用
Multilingual settings of php website (IP address distinguishes domestic and foreign)
C primer plus学习笔记 —— 8、结构体
Unity3D Button mouse hover enter and mouse hover exit button events
CorelDRAW2022 streamlined Asia Pacific new features in detail