咱們提一個需求:給定一個 List<String>
,統計每一個元素出現的全部位置。app
好比,給定 list:["a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"]
,那麼應該返回:
a : [0]
b : [1, 2]
c : [3, 4, 5]
d : [6, 7, 8]
f : [9, 10]
g : [11]函數
很明顯,咱們很適合使用 Map 來完成這件事情:編碼
public static Map<String, List<Integer>> getElementPositions(List<String> list) { Map<String, List<Integer>> positionsMap = new HashMap<>(); for (int i = 0; i < list.size(); i++) { String str = list.get(i); List<Integer> positions = positionsMap.get(str); if (positions == null) { // 若是 positionsMap 還不存在 str 這個鍵及其對應的 List<Integer> positions = new ArrayList<>(1); positionsMap.put(str, positions); // 將 str 及其對應的 positions 放入 positionsMap } positions.add(i); // 將索引加入 str 相關聯的 List<Integer> 中 } return positionsMap; } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 Java8 以前的 API:"); Map<String, List<Integer>> elementPositions = getElementPositions(list); System.out.println(elementPositions); }
運行結果:spa
Java8 時,Map<K, V>
接口添加了一個新的方法,putIfAbsent(K key, V value)
,功能是:
若是當前 Map
不存在鍵 key 或者該 key 關聯的值爲 null
,那麼就執行 put(key, value)
;不然,便不執行 put
操做。該方法等價於以下代碼:3d
(題外話:putIfAbsent
方法與 put
方法同樣,返回的是方法調用以前與參數 key 相關聯的 value)code
使用 putIfAbsent
修改 getElementPositions
方法:索引
public static Map<String, List<Integer>> getElementPositions(List<String> list) { Map<String, List<Integer>> positionsMap = new HashMap<>(); for (int i = 0; i < list.size(); i++) { String str = list.get(i); positionsMap.putIfAbsent(str, new ArrayList<>(1)); // 若是 positionsMap 不存在鍵 str 或者 str 關聯的 List<Integer> 爲 null,那麼就會進行 put;不然不執行 put positionsMap.get(str).add(i); } return positionsMap; } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 putIfAbsent:"); Map<String, List<Integer>> elementPositions = getElementPositions(list); System.out.println(elementPositions); }
運行結果:接口
能夠看到使用 putIfAbsent
以後的 getElementPositions
簡潔了一點,那還能更簡潔嗎?element
查看 Map
接口的方法,能夠發如今 JDK1.8 時,還添加了以下兩個方法:rem
查看 compute
方法的 API 文檔,能夠發現 compute
方法與以下代碼等價
V oldValue = map.get(key); V newValue = remappingFunction.apply(key, oldValue); if (oldValue != null ) { if (newValue != null) map.put(key, newValue); else map.remove(key); } else { // 即 原來的 key 不存在 Map 中或該 key 關聯的 value 爲 null if (newValue != null) map.put(key, newValue); else return null; }
compute
方法和原來 put
方法的區別在於:
put(K key, V value)
方法,若是 key 在 Map
中不存在,那麼直接加入;若是已經存在,那麼使用新的 value 替換舊的 value;
而 compute(K key, BiFunction remappingFunction)
方法能夠經過一個 BiFunction
來計算出新的 value,BiFunction
的參數爲舊的 key 和 value,返回計算出新的 value —— 與 put
方法不一樣,compute
方法返回的會是最新的與 key 相關聯的 value,而不是舊的 value。
因此可使用 compute
方法改寫 getElementPositions
以下:
public static Map<String, List<Integer>> getElementPositions(List<String> list) { Map<String, List<Integer>> positionsMap = new HashMap<>(); for (int i = 0; i < list.size(); i++) { positionsMap.compute(list.get(i), (k, v) -> v == null ? new ArrayList<>(1) : v).add(i); } return positionsMap; } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 compute:"); Map<String, List<Integer>> elementPositions = getElementPositions(list); System.out.println(elementPositions); }
(k, v) -> v == null ? new ArrayList<>(1) : v
即 若是當前的 value 爲 null
,那麼 該 BiFunction
的返回值爲 new ArrayList<>(1)
;若是不爲 null
,那麼返回值即是自己。並且由於 compute
方法會返回新的 value —— 此時即是與 list.get(i)
(key) 相關聯的 ArrayList
—— 因此咱們能夠直接調用其 add
方法。
運行結果:
很棒~ 還能更簡潔嗎? 咱們再看看 computeIfAbsent
方法:computeIfAbsent
和 compute
的關係,就相似於 putIfAbsent
和 put
的關係:computeIfAbsent
在 key 不在 Map
中或者與 key 相關聯的 value 爲 null
時,才執行經過函數計算新 value 的操做,不然不執行;computeIfAbsent
的返回值也是與 key 相關聯的最新的 value。其默認實現以下:
與 compute
不一樣,computeIfAbsent
接受的函數操做是 Function
而不是 BiFunction
—— 這很好理解,computeIfAbsent
只在 key 不在 Map
中或者與 key 相關聯的 value 爲 null
時才執行函數操做,那麼顯然此時與 key 相關的 value 爲 null
,因此 computeIfAbsent
只接受 Function
做爲參數便可 —— 該 Function
可使用 key 做爲參數計算出新的 value。使用 computeIfAbsent
改寫 getElementPositions
:
public static Map<String, List<Integer>> getElementPositions(List<String> list) { Map<String, List<Integer>> positionsMap = new HashMap<>(); for (int i = 0; i < list.size(); i++) { positionsMap.computeIfAbsent(list.get(i), k -> new ArrayList<>(1)).add(i); } return positionsMap; } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 computeIfAbsent:"); Map<String, List<Integer>> elementPositions = getElementPositions(list); System.out.println(elementPositions); }
運行結果:
事實上,本文使用 putIfAbsent
時是存在問題的,positionsMap.putIfAbsent(str, new ArrayList<>(1));
這句代碼每次調用時都會產生一個臨時的 ArrayList
—— 當遍歷的 List<String>
較大時,這可能會帶來必定的負面影響;相比之下 compute
和 computeIfAbsent
的好處在於,它們接受的參數爲函數,只會在必要時才使用函數進行計算得出新 value
。在本文相似需求的狀況下,就適用性和簡潔性而言,computeIfAbsent
要優於 compute
。在 JDK1.8 的 API 文檔中,也說到在須要生成一個相似於 Map<K, Collection<V>>
的結構時,computeIfAbsent
很適合這種狀況:
那 compute
方法適用於什麼狀況呢?從前面的介紹可知,compute
方法更適用於更新 key 關聯的 value 時,新值依賴於舊值的狀況 —— 好比統計一個 List<String>
中每一個元素出現的次數:
public static Map<String, Integer> getElementCounts(List<String> list) { Map<String, Integer> countsMap = new HashMap<>(); list.forEach(str -> countsMap.compute(str, (k, v) -> v == null ? 1 : v + 1)); // 此時:新值 = 舊值 + 1 return countsMap; } public static void main(String[] args) throws Exception { List<String> list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 compute 計算元素出現的次數:"); Map<String, Integer> counts = getElementCounts(list); System.out.println(counts); }
運行結果:
Java8 中還爲 Map
添加了一些其餘方便於編碼的新方法,請有興趣的讀者繼續發掘。