当前位置:网站首页>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.
边栏推荐
- SQL injection Less46 (injection after order by + rand() Boolean blind injection)
- f.grid_sample
- 测试中的误报和漏报同样的值得反复修正
- 局域网电脑硬件信息收集工具
- CefSharp入门-winform
- SQL注入 Less46(order by后的注入+rand()布尔盲注)
- 你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
- Classic linked list OJ strong training problem - fast and slow double pointer efficient solution
- Thesis framework of the opening report
- 7、私信列表
猜你喜欢
Project (5) - Small target detection tph-yolov5
Huawei od dice js
Difference between CMOS and TTL?
Mysql 45讲学习笔记(二十五)MYSQL保证高可用
Mathematics to solve the problem - circular linked list
什么是分布式锁?实现分布式锁的三种方式
CorelDRAW2022 streamlined Asia Pacific new features in detail
Why is String immutable?
Detailed explanation of TCP (3)
Office automation case: how to automatically generate period data?
随机推荐
php 网站的多语言设置(IP地址区分国内国外)
IIR滤波器和FIR滤波器
12 磁盘相关命令
【编译原理】词法分析程序设计原理与实现
7年经验,功能测试工程师该如何一步步提升自己的能力呢?
Office automation case: how to automatically generate period data?
SonarQube的BUG定义
YOLOV5学习笔记(三)——网络模块详解
C# remote debugging
5. SAP ABAP OData 服务如何支持 $filter (过滤)操作
Thesis framework of the opening report
【Cocos Creator 3.5】缓动系统停止所有动画
Mycat's master-slave relationship, vertical sub-database, horizontal sub-table, and detailed configuration of mycat fragmented table query (mysql5.7 series)
19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing
SQL 面试用题(重点)
mycat的主从关系 垂直分库 水平分表 以及mycat分片联表查询的配置详解(mysql5.7系列)
SQL注入 Less54(限制次数的SQL注入+union注入)
11. Redis implements follow, unfollow, and follow and follower lists
MultipartFile file upload
IDEA 注释报红解决