当前位置:网站首页>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.
边栏推荐
猜你喜欢
Huawei od dice js
19. Support Vector Machines - Intuitive Understanding of Optimization Objectives and Large Spacing
【C语言】预处理操作
Mathematics to solve the problem - circular linked list
Why is String immutable?
4. Sensitive word filtering (prefix tree)
Moxa NPort device flaw could expose critical infrastructure to devastating attack
STM32问题合集
4、敏感词过滤(前缀树)
Mysql 45讲学习笔记(二十五)MYSQL保证高可用
随机推荐
分布式系统架构需要解决的问题
STM32问题合集
The simulation application of common mode inductance is here, full of dry goods for everyone
工程(五)——小目标检测tph-yolov5
选好冒烟测试用例,为进入QA的制品包把好第一道关
10、Redis实现点赞(Set)和获取总点赞数
Local area network computer hardware information collection tool
YOLOV5 study notes (2) - environment installation + operation + training
Discussion on Service Commitment of Class Objects under Multithreading
原子操作 CAS
Word/Excel fixed table size, when filling in the content, the table does not change with the cell content
MP使用时的几个常见报错
观察者模式
Why is String immutable?
Mysql 45讲学习笔记(二十四)MYSQL主从一致
【C语言】三子棋(经典解法+一览图)
递归查询单表-单表树结构-(自用)
CentOS7下mysql5.7.37的卸载【完美方案】
Chapter 9 SVM Practice
如何搭建私有yum源