如果连Map是什么你都理解不了,那我相信你也不会看到这里了。
一、Map.entry是什么?
- Map是java中的接口,Map.Entry是Map的一个内部接口。(不信的小伙伴可以自己去看一下源码哟!!!)
- 此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)
- 接口中有getKey(),getValue方法(很重要的两个方法)
说再多你也可能不信,那就:-----> 直接上源码哈
interface Entry<K, V> {
/**
* Returns the key corresponding to this entry.
*
* @return the key corresponding to this entry
* @throws IllegalStateException implementations may, but are not
* required to, throw this exception if the entry has been
* removed from the backing map.
*/
K getKey();
/**
* Returns the value corresponding to this entry. If the mapping
* has been removed from the backing map (by the iterator's
* {@code remove} operation), the results of this call are undefined.
*
* @return the value corresponding to this entry
* @throws IllegalStateException implementations may, but are not
* required to, throw this exception if the entry has been
* removed from the backing map.
*/
V getValue();
//...........其它一些方法,有需要的小伙伴自行去查看源码
- Map.entry的实现类是Map子类里面的一个静态的内部类(强烈建议大家去看一下源码)
以HashMap为例,我带大家再看看第四点(HashMap源码内有个内部实现了Map.entry接口)
请看图
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
public final K getKey() {
return key;
}
public final V getValue() {
return value;
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//..........剩下的不再复制过来,有需要自行去查看
}
二、Map如何遍历?
要盖房子必须要有砖,同理要知道如何遍历Map,那就要有以下一些知识储备
- V put(K key, V value):向Map中添加key-value
- V get(K key): 获取指定key的value,不存在返回null
- V remove(K key): 删除指定key的键值对,返回value
- Set< K > keySet(): 从Map中得到key的集合
- Set<Map.Entry<K, V>> entrySet(): 从Map集合中得到内部接口Entry的集合
遍历方法:
直接上代码哈
//4.map遍历学习
public static void test4()
{
Map<String, String> map = new HashMap<String, String>();
//存入数据
map.put("我的公众号", "放牛娃学编程");
map.put("口号", "分享与热爱");
map.put("爱好", "一起交流学习呀呀");
//1.普遍使用 (效率低下,大量数据时不推荐使用)
for(String key: map.keySet())
{
System.out.println(key+"------> "+map.get(key));
}
//2.Map.entrySet来遍历 (推荐使用这种方法)
for(Map.Entry<String, String> entry: map.entrySet())
{
System.out.println(entry.getKey()+"---------> "+entry.getValue());
}
//3.使用迭代器来遍历
System.out.println("----------通过iterator遍历key和value-----");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<String, String> entry = it.next();
System.out.println(entry.getKey()+"---------> "+entry.getValue());
}
//4.通过map.value (直接遍历value)
for(String value: map.values())
{
System.out.println("value="+value);
}
}
三、分享结束
最后有兴趣一起交流的,可以关注我的公众号:这里你能够学到很实用的技巧,不是常用的我不说,公众号回复提取码即可获取以下学习资料啦啦啦啦,喜欢就拿去吧!!
-
Java web从入门到精通电子书
-
Python机器学习电子书
-
Python400集(北京尚学堂)
-
JavaScript项目案例、经典面试题
-
Java300集(入门、精通)
-
Java后端培训机构录集(同事培训内部提供)