类关系

image.png

简略版类图 Map - 图2

功能介绍

包路径【在哪里】:java.util

功能描述【有什么用】:一个可以映射键-值对的对象。一个Map中不允许存在重复相同的key,而任何一个key仅能映射一个value。

An object that maps keys to values. A map cannot contain duplicate keys;* each key can map to at most one value. _This interface takes the place of the Dictionary class, which* was a totally abstract class rather than an interface.

源码解析

  1. /**
  2. * An object that maps keys to values. A map cannot contain duplicate keys;
  3. * each key can map to at most one value.
  4. *
  5. * @param <K> the type of keys maintained by this map 当前映射维护的key的java类型
  6. * @param <V> the type of mapped values 当前映射维护的value的类型
  7. *
  8. * @author Josh Bloch
  9. * @see HashMap
  10. * @see TreeMap
  11. * @see Hashtable
  12. * @see SortedMap
  13. * @see Collection
  14. * @see Set
  15. * @since 1.2
  16. */
  17. public interface Map<K,V> {
  18. // Query Operations 查找操作
  19. /**
  20. * Returns the number of key-value mappings in this map. If the
  21. * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
  22. * <tt>Integer.MAX_VALUE</tt>.
  23. *
  24. * 返回当前映射集合的映射记录数【即键值对数】,
  25. * 如果当前键值对条数超出Integer.MAX_VALUE,则返回Integer.MAX_VALUE
  26. *
  27. * @return the number of key-value mappings in this map
  28. */
  29. int size();
  30. /**
  31. * Returns <tt>true</tt> if this map contains no key-value mappings.
  32. *
  33. * 判断当前Map映射是否存在键值对元素,如果存在则返回true
  34. *
  35. * @return <tt>true</tt> if this map contains no key-value mappings
  36. */
  37. boolean isEmpty();
  38. /**
  39. * Returns <tt>true</tt> if this map contains a mapping for the specified
  40. * key. More formally, returns <tt>true</tt> if and only if
  41. * this map contains a mapping for a key <tt>k</tt> such that
  42. * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
  43. * at most one such mapping.)
  44. *
  45. * 判断当前Map映射是否存在目标key的映射,如果存在则返回true
  46. *
  47. * @param key key whose presence in this map is to be tested 目标key
  48. * @return <tt>true</tt> if this map contains a mapping for the specified
  49. * key
  50. *
  51. * @throws ClassCastException if the key is of an inappropriate type for
  52. * this map 如果目标key和当前映射的K类型【即key的类型】不一致则抛出ClassCastException异常
  53. *
  54. */
  55. boolean containsKey(Object key);
  56. /**
  57. * Returns <tt>true</tt> if this map maps one or more keys to the
  58. * specified value. More formally, returns <tt>true</tt> if and only if
  59. * this map contains at least one mapping to a value <tt>v</tt> such that
  60. * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation
  61. * will probably require time linear in the map size for most
  62. * implementations of the <tt>Map</tt> interface.
  63. *
  64. * 判断当前映射是否存在对应的值value的映射,如果存在则返回true
  65. *
  66. * @param value value whose presence in this map is to be tested 目标value
  67. * @return <tt>true</tt> if this map maps one or more keys to the
  68. * specified value
  69. * @throws ClassCastException if the value is of an inappropriate type for
  70. * this map 如果目标value和当前映射的V类型【即value的类型】不一致则抛出ClassCastException异常
  71. */
  72. boolean containsValue(Object value);
  73. /**
  74. * Returns the value to which the specified key is mapped,
  75. * or {@code null} if this map contains no mapping for the key.
  76. *
  77. * 根据传入的key获取当前映射中对应的value,如果存在对应映射关系,则返回对应值,否则返回null
  78. *
  79. * <p>More formally, if this map contains a mapping from a key
  80. * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
  81. * key.equals(k))}, then this method returns {@code v}; otherwise
  82. * it returns {@code null}. (There can be at most one such mapping.)
  83. *
  84. * @param key the key whose associated value is to be returned 指定返回value的key
  85. * @return the value to which the specified key is mapped, or
  86. * {@code null} if this map contains no mapping for the key
  87. * @throws ClassCastException if the key is of an inappropriate type for
  88. * this map 如果目标key和当前映射的K类型【即key的类型】不一致则抛出ClassCastException异常
  89. */
  90. V get(Object key);
  91. // Modification Operations 变更操作
  92. /**
  93. * Associates the specified value with the specified key in this map
  94. * (optional operation). If the map previously contained a mapping for
  95. * the key, the old value is replaced by the specified value. (A map
  96. * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
  97. * if {@link #containsKey(Object) m.containsKey(k)} would return
  98. * <tt>true</tt>.)
  99. *
  100. * 向当前Map映射中存放键值对,当已存在key对应的映射时,使用传入的value覆盖旧的value,value允许为null
  101. *
  102. * @param key key with which the specified value is to be associated 键
  103. * @param value value to be associated with the specified key 值
  104. *
  105. * @return the previous value associated with <tt>key</tt>, or
  106. * <tt>null</tt> if there was no mapping for <tt>key</tt>.
  107. * (A <tt>null</tt> return can also indicate that the map
  108. * previously associated <tt>null</tt> with <tt>key</tt>,
  109. * if the implementation supports <tt>null</tt> values.)
  110. *
  111. * 返回值是key先前对应的value,如果没有key对应的映射,那么返回null
  112. *
  113. * @throws UnsupportedOperationException if the <tt>put</tt> operation
  114. * is not supported by this map 如果当前Map映射不允许put操作,抛出异常
  115. *
  116. * @throws ClassCastException if the class of the specified key or value
  117. * prevents it from being stored in this map 如果目标key和当前映射的K类型【即key的类型】不一致则抛出ClassCastException异常
  118. *
  119. * @throws NullPointerException if the specified key or value is null
  120. * and this map does not permit null keys or values 如果目标value和当前映射的V类型【即value的类型】不一致则抛出ClassCastException异常
  121. *
  122. * @throws IllegalArgumentException if some property of the specified key
  123. * or value prevents it from being stored in this map 如果该map阻止保存指定key或value的某些属性,抛出IllegalArgumentException异常
  124. */
  125. V put(K key, V value);
  126. /**
  127. * Removes the mapping for a key from this map if it is present
  128. * (optional operation). More formally, if this map contains a mapping
  129. * from key <tt>k</tt> to value <tt>v</tt> such that
  130. * <code>(key==null ? k==null : key.equals(k))</code>, that mapping
  131. * is removed. (The map can contain at most one such mapping.)
  132. *
  133. * 从当前Map映射中移除以目标key为键的映射关系,并返回key对应的value,如果没有映射关系则返回null
  134. *
  135. * <p>Returns the value to which this map previously associated the key,
  136. * or <tt>null</tt> if the map contained no mapping for the key.
  137. *
  138. * <p>If this map permits null values, then a return value of
  139. * <tt>null</tt> does not <i>necessarily</i> indicate that the map
  140. * contained no mapping for the key; it's also possible that the map
  141. * explicitly mapped the key to <tt>null</tt>.
  142. *
  143. * <p>The map will not contain a mapping for the specified key once the
  144. * call returns.
  145. *
  146. * @param key key whose mapping is to be removed from the map 目标key
  147. * @return the previous value associated with <tt>key</tt>, or
  148. * <tt>null</tt> if there was no mapping for <tt>key</tt>. 返回目标key对应的value
  149. * @throws UnsupportedOperationException if the <tt>remove</tt> operation
  150. * is not supported by this map 如果当前Map不允许remove操作,则抛出UnsupportedOperationException异常
  151. * @throws ClassCastException if the key is of an inappropriate type for
  152. * this map
  153. */
  154. V remove(Object key);
  155. // Bulk Operations 扩展操作
  156. /**
  157. * Copies all of the mappings from the specified map to this map
  158. * (optional operation). The effect of this call is equivalent to that
  159. * of calling {@link #put(Object,Object) put(k, v)} on this map once
  160. * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
  161. * specified map. The behavior of this operation is undefined if the
  162. * specified map is modified while the operation is in progress.
  163. *
  164. * 从指定的map中拷贝所有的映射到该map中。
  165. *
  166. * @param m mappings to be stored in this map
  167. * @throws UnsupportedOperationException if the <tt>putAll</tt> operation
  168. * is not supported by this map
  169. * @throws ClassCastException if the class of a key or value in the
  170. * specified map prevents it from being stored in this map
  171. * @throws NullPointerException if the specified map is null, or if
  172. * this map does not permit null keys or values, and the
  173. * specified map contains null keys or values
  174. * 如果目标Map为null,或者当前Map不允许存在null的key或value,而目标Map中存在,则抛出异常
  175. *
  176. * @throws IllegalArgumentException if some property of a key or value in
  177. * the specified map prevents it from being stored in this map
  178. */
  179. void putAll(Map<? extends K, ? extends V> m);
  180. /**
  181. * Removes all of the mappings from this map (optional operation).
  182. * The map will be empty after this call returns.
  183. * 清空当前Map所有映射
  184. * @throws UnsupportedOperationException if the <tt>clear</tt> operation
  185. * is not supported by this map
  186. */
  187. void clear();
  188. // Views 视图
  189. /**
  190. * Returns a {@link Set} view of the keys contained in this map.
  191. * The set is backed by the map, so changes to the map are
  192. * reflected in the set, and vice-versa. If the map is modified
  193. * while an iteration over the set is in progress (except through
  194. * the iterator's own <tt>remove</tt> operation), the results of
  195. * the iteration are undefined. The set supports element removal,
  196. * which removes the corresponding mapping from the map, via the
  197. * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
  198. * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
  199. * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
  200. * operations.
  201. *
  202. * 返回该map中所有key的Set视图。
  203. * 该set是由map支持的,所以对map的更改将影响到set,反之亦然。
  204. * 如果在迭代set的过程中map被修改了(除了迭代器使用自己的remove操作),那么迭代的结果是undefined。
  205. * 该set支持删除map中映射的操作,其中方法包括Iterator.remove、Set.remove、removeAll、retainAll及clear。
  206. * 但是不支持add或addAll操作。
  207. *
  208. * @return a set view of the keys contained in this map
  209. */
  210. Set<K> keySet();
  211. /**
  212. * Returns a {@link Collection} view of the values contained in this map.
  213. * The collection is backed by the map, so changes to the map are
  214. * reflected in the collection, and vice-versa. If the map is
  215. * modified while an iteration over the collection is in progress
  216. * (except through the iterator's own <tt>remove</tt> operation),
  217. * the results of the iteration are undefined. The collection
  218. * supports element removal, which removes the corresponding
  219. * mapping from the map, via the <tt>Iterator.remove</tt>,
  220. * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
  221. * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
  222. * support the <tt>add</tt> or <tt>addAll</tt> operations.
  223. *
  224. * 返回该map中所有value的Collection视图。
  225. * 该collection是由map支持的,所以对map的更改将影响到collection,反之亦然。
  226. * 如果在迭代collection的过程中map被修改了(除了迭代器使用自己的remove操作),那么迭代的结果是undefined。
  227. * 该collection支持删除map中映射的操作,其中方法包括Iterator.remove、Collection.remove、removeAll、retainAll及clear。
  228. * 但是不支持add或addAll操作。
  229. *
  230. * @return a collection view of the values contained in this map
  231. */
  232. Collection<V> values();
  233. /**
  234. * Returns a {@link Set} view of the mappings contained in this map.
  235. * The set is backed by the map, so changes to the map are
  236. * reflected in the set, and vice-versa. If the map is modified
  237. * while an iteration over the set is in progress (except through
  238. * the iterator's own <tt>remove</tt> operation, or through the
  239. * <tt>setValue</tt> operation on a map entry returned by the
  240. * iterator) the results of the iteration are undefined. The set
  241. * supports element removal, which removes the corresponding
  242. * mapping from the map, via the <tt>Iterator.remove</tt>,
  243. * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
  244. * <tt>clear</tt> operations. It does not support the
  245. * <tt>add</tt> or <tt>addAll</tt> operations.
  246. *
  247. * 返回该map中所有映射的Set视图。
  248. * 该set是由map支持的,所以对map的更改将影响到set,反之亦然。
  249. * 如果在迭代set的过程中map被修改了(除了迭代器使用自己的remove操作,或者setValue操作),那么迭代的结果是undefined
  250. * 该set支持删除map中映射的操作,其中方法包括Iterator.remove、Set.remove、removeAll、retainAll及clear。
  251. * 但是不支持add或addAll操作。
  252. *
  253. * @return a set view of the mappings contained in this map
  254. */
  255. Set<Map.Entry<K, V>> entrySet();
  256. /**
  257. * A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns
  258. * a collection-view of the map, whose elements are of this class. The
  259. * <i>only</i> way to obtain a reference to a map entry is from the
  260. * iterator of this collection-view. These <tt>Map.Entry</tt> objects are
  261. * valid <i>only</i> for the duration of the iteration; more formally,
  262. * the behavior of a map entry is undefined if the backing map has been
  263. * modified after the entry was returned by the iterator, except through
  264. * the <tt>setValue</tt> operation on the map entry.
  265. *
  266. * 一条map的记录(一个键值对)。
  267. * Map.entrySet方法返回的collection视图中的元素就是这个类(Entry)。
  268. * 唯一一个获得entry引用的方式,是从collection视图的迭代器中获取。
  269. * 这些Map.Entry对象只在迭代期间有效;
  270. * 如果在entry的迭代器返回后,作为支持的map被修改了(除了entry的setValue操作),那么entry的行为是未定义的。
  271. *
  272. * @see Map#entrySet()
  273. * @since 1.2
  274. */
  275. interface Entry<K,V> {
  276. /**
  277. * Returns the key corresponding to this entry.
  278. *
  279. * 返回该entry对应的key。
  280. *
  281. * @return the key corresponding to this entry
  282. * @throws IllegalStateException implementations may, but are not
  283. * required to, throw this exception if the entry has been
  284. * removed from the backing map. 如果entry已经被支持的map中删除了,抛出IllegalStateException异常
  285. */
  286. K getKey();
  287. /**
  288. * Returns the value corresponding to this entry. If the mapping
  289. * has been removed from the backing map (by the iterator's
  290. * <tt>remove</tt> operation), the results of this call are undefined.
  291. *
  292. * 返回该entry对应的value。
  293. * 如果在作为支持的map中删除了该映射(用迭代器的remove操作),则返回undefined。
  294. *
  295. * @return the value corresponding to this entry
  296. * @throws IllegalStateException implementations may, but are not
  297. * required to, throw this exception if the entry has been
  298. * removed from the backing map.
  299. */
  300. V getValue();
  301. /**
  302. * Replaces the value corresponding to this entry with the specified
  303. * value (optional operation). (Writes through to the map.) The
  304. * behavior of this call is undefined if the mapping has already been
  305. * removed from the map (by the iterator's <tt>remove</tt> operation).
  306. *
  307. * 设置该entry对应的value
  308. *
  309. * @param value new value to be stored in this entry
  310. * @return old value corresponding to the entry
  311. * @throws UnsupportedOperationException if the <tt>put</tt> operation
  312. * is not supported by the backing map
  313. * @throws ClassCastException if the class of the specified value
  314. * prevents it from being stored in the backing map
  315. * @throws NullPointerException if the backing map does not permit
  316. * null values, and the specified value is null
  317. * @throws IllegalArgumentException if some property of this value
  318. * prevents it from being stored in the backing map
  319. * @throws IllegalStateException implementations may, but are not
  320. * required to, throw this exception if the entry has been
  321. * removed from the backing map.
  322. */
  323. V setValue(V value);
  324. /**
  325. * Compares the specified object with this entry for equality.
  326. * Returns <tt>true</tt> if the given object is also a map entry and
  327. * the two entries represent the same mapping. More formally, two
  328. * entries <tt>e1</tt> and <tt>e2</tt> represent the same mapping
  329. * if<pre>
  330. * (e1.getKey()==null ?
  331. * e2.getKey()==null : e1.getKey().equals(e2.getKey())) &amp;&amp;
  332. * (e1.getValue()==null ?
  333. * e2.getValue()==null : e1.getValue().equals(e2.getValue()))
  334. * </pre>
  335. * This ensures that the <tt>equals</tt> method works properly across
  336. * different implementations of the <tt>Map.Entry</tt> interface.
  337. *
  338. * 比较两个entry,如果两个entry映射一样【ker和value完全一致】,返回true
  339. *
  340. * @param o object to be compared for equality with this map entry
  341. * @return <tt>true</tt> if the specified object is equal to this map
  342. * entry
  343. */
  344. boolean equals(Object o);
  345. /**
  346. * Returns the hash code value for this map entry. The hash code
  347. * of a map entry <tt>e</tt> is defined to be: <pre>
  348. * (e.getKey()==null ? 0 : e.getKey().hashCode()) ^
  349. * (e.getValue()==null ? 0 : e.getValue().hashCode())
  350. * </pre>
  351. * This ensures that <tt>e1.equals(e2)</tt> implies that
  352. * <tt>e1.hashCode()==e2.hashCode()</tt> for any two Entries
  353. * <tt>e1</tt> and <tt>e2</tt>, as required by the general
  354. * contract of <tt>Object.hashCode</tt>.
  355. *
  356. * @return the hash code value for this map entry
  357. * @see Object#hashCode()
  358. * @see Object#equals(Object)
  359. * @see #equals(Object)
  360. */
  361. int hashCode();
  362. /**
  363. * Returns a comparator that compares {@link Map.Entry} in natural order on key.
  364. *
  365. * <p>The returned comparator is serializable and throws {@link
  366. * NullPointerException} when comparing an entry with a null key.
  367. *
  368. * 返回一个比较器,通过比较entry的key来确定entry之间的大小
  369. *
  370. * @param <K> the {@link Comparable} type of then map keys
  371. * @param <V> the type of the map values
  372. * @return a comparator that compares {@link Map.Entry} in natural order on key.
  373. * @see Comparable
  374. * @since 1.8
  375. */
  376. public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
  377. return (Comparator<Map.Entry<K, V>> & Serializable)
  378. (c1, c2) -> c1.getKey().compareTo(c2.getKey()); //比较key大小,使用的是lambda表达式
  379. }
  380. /**
  381. * Returns a comparator that compares {@link Map.Entry} in natural order on value.
  382. *
  383. * <p>The returned comparator is serializable and throws {@link
  384. * NullPointerException} when comparing an entry with null values.
  385. *
  386. * 返回一个比较器,通过比较entry的value来确定entry之间的大小
  387. *
  388. * @param <K> the type of the map keys
  389. * @param <V> the {@link Comparable} type of the map values
  390. * @return a comparator that compares {@link Map.Entry} in natural order on value.
  391. * @see Comparable
  392. * @since 1.8
  393. */
  394. public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
  395. return (Comparator<Map.Entry<K, V>> & Serializable)
  396. (c1, c2) -> c1.getValue().compareTo(c2.getValue());
  397. }
  398. /**
  399. * Returns a comparator that compares {@link Map.Entry} by key using the given
  400. * {@link Comparator}.
  401. *
  402. * <p>The returned comparator is serializable if the specified comparator
  403. * is also serializable.
  404. *
  405. * 返回一个用于比较entry的比较器,比较规则使用传入的参数对key进行比较
  406. *
  407. * @param <K> the type of the map keys
  408. * @param <V> the type of the map values
  409. * @param cmp the key {@link Comparator}
  410. * @return a comparator that compares {@link Map.Entry} by the key.
  411. * @since 1.8
  412. */
  413. public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
  414. Objects.requireNonNull(cmp);
  415. return (Comparator<Map.Entry<K, V>> & Serializable)
  416. (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
  417. }
  418. /**
  419. * Returns a comparator that compares {@link Map.Entry} by value using the given
  420. * {@link Comparator}.
  421. *
  422. * <p>The returned comparator is serializable if the specified comparator
  423. * is also serializable.
  424. *
  425. * 返回一个用于比较entry的比较器,比较规则使用传入的参数对value进行比较
  426. *
  427. * @param <K> the type of the map keys
  428. * @param <V> the type of the map values
  429. * @param cmp the value {@link Comparator}
  430. * @return a comparator that compares {@link Map.Entry} by the value.
  431. * @since 1.8
  432. */
  433. public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
  434. Objects.requireNonNull(cmp);
  435. return (Comparator<Map.Entry<K, V>> & Serializable)
  436. (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
  437. }
  438. }
  439. // Comparison and hashing 比较和哈希
  440. /**
  441. * Compares the specified object with this map for equality. Returns
  442. * <tt>true</tt> if the given object is also a map and the two maps
  443. * represent the same mappings. More formally, two maps <tt>m1</tt> and
  444. * <tt>m2</tt> represent the same mappings if
  445. * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
  446. * <tt>equals</tt> method works properly across different implementations
  447. * of the <tt>Map</tt> interface.
  448. * 比较两个Map是否相等
  449. * @param o object to be compared for equality with this map
  450. * @return <tt>true</tt> if the specified object is equal to this map
  451. */
  452. boolean equals(Object o);
  453. /**
  454. * Returns the hash code value for this map. The hash code of a map is
  455. * defined to be the sum of the hash codes of each entry in the map's
  456. * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt>
  457. * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps
  458. * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of
  459. * {@link Object#hashCode}.
  460. *
  461. * map的equals方法,判断两个map中的键值对集合是不是相同
  462. *
  463. * @return the hash code value for this map
  464. * @see Map.Entry#hashCode()
  465. * @see Object#equals(Object)
  466. * @see #equals(Object)
  467. */
  468. int hashCode();
  469. // Defaultable methods 默认方法
  470. /**
  471. * Returns the value to which the specified key is mapped, or
  472. * {@code defaultValue} if this map contains no mapping for the key.
  473. *
  474. * map中存在键为key的value就返回该value,不存在则返回一个默认值defaultValue
  475. *
  476. * @since 1.8
  477. */
  478. default V getOrDefault(Object key, V defaultValue) {
  479. V v;
  480. return (((v = get(key)) != null) || containsKey(key))
  481. ? v
  482. : defaultValue;
  483. }
  484. /**
  485. * Performs the given action for each entry in this map until all entries
  486. * have been processed or the action throws an exception. Unless
  487. * otherwise specified by the implementing class, actions are performed in
  488. * the order of entry set iteration (if an iteration order is specified.)
  489. * Exceptions thrown by the action are relayed to the caller.
  490. *
  491. * 效果等同于for(Entry entry:Map.entrySet()),即遍历map中的entryset
  492. *
  493. * @since 1.8
  494. */
  495. default void forEach(BiConsumer<? super K, ? super V> action) {
  496. Objects.requireNonNull(action);
  497. // 使用lambda表达式
  498. for (Map.Entry<K, V> entry : entrySet()) {
  499. K k;
  500. V v;
  501. try {
  502. k = entry.getKey();
  503. v = entry.getValue();
  504. } catch(IllegalStateException ise) {
  505. // this usually means the entry is no longer in the map.
  506. throw new ConcurrentModificationException(ise);
  507. }
  508. action.accept(k, v); //执行某个操作,由参数BiConsumer函数对象决定
  509. }
  510. }
  511. /**
  512. * Replaces each entry's value with the result of invoking the given
  513. * function on that entry until all entries have been processed or the
  514. * function throws an exception. Exceptions thrown by the function are
  515. * relayed to the caller.
  516. *
  517. * 遍历整个map中的entry,将所有key的value值替换为某个新值,新值由function对象的apply方法的返回值决定
  518. *
  519. * @param function the function to apply to each entry
  520. *
  521. * removed during iteration
  522. * @since 1.8
  523. */
  524. default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
  525. Objects.requireNonNull(function);
  526. // 遍历entrySet
  527. for (Map.Entry<K, V> entry : entrySet()) {
  528. K k;
  529. V v;
  530. try {
  531. k = entry.getKey();
  532. v = entry.getValue();
  533. } catch(IllegalStateException ise) {
  534. // this usually means the entry is no longer in the map.
  535. throw new ConcurrentModificationException(ise);
  536. }
  537. // ise thrown from function is not a cme.
  538. v = function.apply(k, v); // 执行函数方法并获得返回值
  539. try {
  540. entry.setValue(v);
  541. } catch(IllegalStateException ise) {
  542. // this usually means the entry is no longer in the map.
  543. throw new ConcurrentModificationException(ise);
  544. }
  545. }
  546. }
  547. /**
  548. * If the specified key is not already associated with a value (or is mapped
  549. * to {@code null}) associates it with the given value and returns
  550. * {@code null}, else returns the current value.
  551. *
  552. * 向Map中设置键值对,如果当前Map中已经存在当前key对应的映射,则直接返回原映射值,否则设置后返回value
  553. *
  554. * @param key key with which the specified value is to be associated
  555. * @param value value to be associated with the specified key
  556. * @return the previous value associated with the specified key, or
  557. * {@code null} if there was no mapping for the key.
  558. * (A {@code null} return can also indicate that the map
  559. * previously associated {@code null} with the key,
  560. * if the implementation supports null values.)
  561. * @since 1.8
  562. */
  563. default V putIfAbsent(K key, V value) {
  564. V v = get(key);
  565. if (v == null) {
  566. v = put(key, value);
  567. }
  568. return v;
  569. }
  570. /**
  571. * Removes the entry for the specified key only if it is currently
  572. * mapped to the specified value.
  573. *
  574. * 移除键值对,只有当Map中对应key的value值与传入的value值相等时,才会移除键值对,否则返回false
  575. *
  576. * @param key key with which the specified value is associated
  577. * @param value value expected to be associated with the specified key
  578. * @return {@code true} if the value was removed
  579. * @since 1.8
  580. */
  581. default boolean remove(Object key, Object value) {
  582. Object curValue = get(key);
  583. if (!Objects.equals(curValue, value) ||
  584. (curValue == null && !containsKey(key))) {
  585. return false;
  586. }
  587. remove(key);
  588. return true;
  589. }
  590. /**
  591. * Replaces the entry for the specified key only if currently
  592. * mapped to the specified value.
  593. *
  594. * 替换键值,只有当传入的key在Map中存在对应值,且oldValue与原先的值相等时才会替换新的值newValue
  595. *
  596. * @param key key with which the specified value is associated
  597. * @param oldValue value expected to be associated with the specified key
  598. * @param newValue value to be associated with the specified key
  599. * @return {@code true} if the value was replaced
  600. *
  601. * @since 1.8
  602. */
  603. default boolean replace(K key, V oldValue, V newValue) {
  604. Object curValue = get(key);
  605. if (!Objects.equals(curValue, oldValue) ||
  606. (curValue == null && !containsKey(key))) {
  607. return false;
  608. }
  609. put(key, newValue);
  610. return true;
  611. }
  612. /**
  613. * Replaces the entry for the specified key only if it is
  614. * currently mapped to some value.
  615. *
  616. * 替换键值对,只有原先Map中存在传入的key对应映射关系,才会进行替换
  617. *
  618. * @param key key with which the specified value is associated
  619. * @param value value to be associated with the specified key
  620. * @return the previous value associated with the specified key, or
  621. * {@code null} if there was no mapping for the key.
  622. * (A {@code null} return can also indicate that the map
  623. * previously associated {@code null} with the key,
  624. * if the implementation supports null values.)
  625. * @since 1.8
  626. */
  627. default V replace(K key, V value) {
  628. V curValue;
  629. if (((curValue = get(key)) != null) || containsKey(key)) {
  630. curValue = put(key, value);
  631. }
  632. return curValue;
  633. }
  634. /**
  635. * If the specified key is not already associated with a value (or is mapped
  636. * to {@code null}), attempts to compute its value using the given mapping
  637. * function and enters it into this map unless {@code null}.
  638. *
  639. * 若key对应的value为null,则将value替换成mappingFunction中apply方法的返回值
  640. *
  641. * @param key key with which the specified value is to be associated
  642. * @param mappingFunction the function to compute a value
  643. * @return the current (existing or computed) value associated with
  644. * the specified key, or null if the computed value is null
  645. *
  646. * @since 1.8
  647. */
  648. default V computeIfAbsent(K key,
  649. Function<? super K, ? extends V> mappingFunction) {
  650. Objects.requireNonNull(mappingFunction);
  651. V v;
  652. // 如果当前Map中key对应的value为null或不存在当前key映射
  653. if ((v = get(key)) == null) {
  654. V newValue;
  655. // 执行mappingFunction中apply方法后返回值赋值给newValue,如果newValue不为null,则设置key-newValue映射关系
  656. if ((newValue = mappingFunction.apply(key)) != null) {
  657. put(key, newValue);
  658. return newValue; // 返回newValue
  659. }
  660. }
  661. return v;
  662. }
  663. /**
  664. * If the value for the specified key is present and non-null, attempts to
  665. * compute a new mapping given the key and its current mapped value.
  666. *
  667. * 若当前Map映射中,key对应的value不为null,则将value替换成remappingFunction中apply方法的返回值
  668. *
  669. * @param key key with which the specified value is to be associated
  670. * @param remappingFunction the function to compute a value
  671. * @return the new value associated with the specified key, or null if none
  672. * @since 1.8
  673. */
  674. default V computeIfPresent(K key,
  675. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  676. Objects.requireNonNull(remappingFunction);
  677. V oldValue;
  678. // 如果当前key对应的值不为null
  679. if ((oldValue = get(key)) != null) {
  680. // 则将执行remappingFunction中apply方法返回值赋值给newValue
  681. V newValue = remappingFunction.apply(key, oldValue);
  682. // 如果newValue不为null
  683. if (newValue != null) {
  684. put(key, newValue); // 使用newValue替代oldValue
  685. return newValue;
  686. } else {
  687. remove(key); // 如果newValue为null,则移除key映射
  688. return null;
  689. }
  690. } else {
  691. return null;
  692. }
  693. }
  694. /**
  695. * Attempts to compute a mapping for the specified key and its current
  696. * mapped value (or {@code null} if there is no current mapping). For
  697. * example, to either create or append a {@code String} msg to a value
  698. * mapping:
  699. *
  700. *
  701. *
  702. * @param key key with which the specified value is to be associated
  703. * @param remappingFunction the function to compute a value
  704. * @return the new value associated with the specified key, or null if none
  705. * @since 1.8
  706. */
  707. default V compute(K key,
  708. BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
  709. Objects.requireNonNull(remappingFunction);
  710. V oldValue = get(key);
  711. V newValue = remappingFunction.apply(key, oldValue);
  712. if (newValue == null) {
  713. // delete mapping
  714. if (oldValue != null || containsKey(key)) {
  715. // something to remove
  716. remove(key);
  717. return null;
  718. } else {
  719. // nothing to do. Leave things as they were.
  720. return null;
  721. }
  722. } else {
  723. // add or replace old mapping
  724. put(key, newValue);
  725. return newValue;
  726. }
  727. }
  728. /**
  729. * If the specified key is not already associated with a value or is
  730. * associated with null, associates it with the given non-null value.
  731. * Otherwise, replaces the associated value with the results of the given
  732. * remapping function, or removes if the result is {@code null}. This
  733. * method may be of use when combining multiple mapped values for a key.
  734. * For example, to either create or append a {@code String msg} to a
  735. * value mapping:
  736. *
  737. *
  738. *
  739. * @param key key with which the resulting value is to be associated
  740. * @param value the non-null value to be merged with the existing value
  741. * associated with the key or, if no existing value or a null value
  742. * is associated with the key, to be associated with the key
  743. * @param remappingFunction the function to recompute a value if present
  744. * @return the new value associated with the specified key, or null if no
  745. * value is associated with the key
  746. * @since 1.8
  747. */
  748. default V merge(K key, V value,
  749. BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
  750. Objects.requireNonNull(remappingFunction);
  751. Objects.requireNonNull(value);
  752. V oldValue = get(key);
  753. // 如果当前Map中key对应的值为null,则将传入参数赋值给newValue
  754. // 否则将执行remappingFunction.apply方法返回值赋值给newValue
  755. V newValue = (oldValue == null) ? value :
  756. remappingFunction.apply(oldValue, value);
  757. // 如果newValue为null,则移除key映射
  758. if(newValue == null) {
  759. remove(key);
  760. } else {
  761. // 否则设置key-newValue映射
  762. put(key, newValue);
  763. }
  764. return newValue;
  765. }
  766. }

简单用法

public static void main(String[] args) {
    Map<Integer,Object> map = new HashMap<Integer, Object>();
    map.put(1,256);
    map.put(2,"测试");

    System.out.println("遍历keySet形式调用");
    for(Integer key : map.keySet()){
        System.out.println("key="+key+",value="+map.get(key));
    }

    System.out.println("\n遍历entrySet形式调用");
    for(Map.Entry entry : map.entrySet()){
        System.out.println("key="+entry.getKey()+",value="+entry.getValue());
    }

}

image.png

总结

1、Map是一个接口,一个可以映射键-值对的对象,其中K代表键的类型,V代表值的类型

2、一个Map中不允许存在重复相同的key,且任何一个key仅能映射一个value。

3、Map内部维护了一个
Entry接口,该接口对应单个映射关系,即一个键值对关系。该接口提供对Map中键值的获取、设置、比较等操作。**

思考

1、put与putIfAbsent的区别?
**
put方法,无论先前是否存在对应key的映射,也无论先前value是否为null,直接覆盖或设新建传入的key-value键值对

putIfAbsent方法,如果先前已存在对应key的映射,则不进行覆盖并返回先前的value。否则新建key-value键值对

2、
是否可以使用Map作为缓存使用?

Map作为**本地缓存,优点是轻量以及快速,生命周期随着 jvm 的销毁而结束。缺点是当存在多实例的时候,每个实例都需要各自保存一份缓存,缓存不具有一致性**。

对标Redis作为分布式缓存来讲,不随JVM销毁而结束,且在多实例的情况下,各实例共用一份缓存,具备数据一致性。缺点就是架构上的复杂性,需保证Redis的可用性

3、Map是否继承了Collection接口?

Collection是List、Set父接口,不是Map父接口。**