1 2 3 4 5 6 7 8 9 10
|
public static void main(String[] args) { Map<String, Integer> stringLength = new HashMap<>(); stringLength.put("John", 2); int i = stringLength.computeIfAbsent("John", String::length); System.out.println("i = " + i); System.out.println("stringLength = " + stringLength); }
|
這段程式碼看起來沒有明顯的錯誤,但可以做一些優化。
1 2 3 4 5 6 7 8 9 10
| public void setNotifyIMap(FileTempRecord record) { List<FileTempRecord> fileTempRecords = SSE_NOTIFY_IMAP.get(record.getCreatedBy()); if (fileTempRecords == null || fileTempRecords.size() < 1) { fileTempRecords = new ArrayList<>(); fileTempRecords.add(record); } else { fileTempRecords.add(record); } SSE_NOTIFY_IMAP.put(record.getCreatedBy(), fileTempRecords); }
|
使用 computeIfAbsent() 方法
現在的程式碼需要先檢查一下 map 中是否有對應的 List,如果沒有的話就要建立一個新的 List。這個過程可以使用 computeIfAbsent() 方法來簡化,如下所示:
1 2 3
| public void setNotifyIMap(FileTempRecord record) { SSE_NOTIFY_IMAP.computeIfAbsent(record.getCreatedBy(), k -> new ArrayList<>()).add(record); }
|
這樣,如果 SSE_NOTIFY_IMAP 中沒有對應的 List,computeIfAbsent() 方法會自動建立一個新的 ArrayList,並將 record 新增到 List 中。
使用 Collection#addAll()
在原始程式碼中,如果 SSE_NOTIFY_IMAP 中已經有對應的 List,就需要分別使用 add() 方法來新增 record。實際上,我們可以使用 Collection#addAll() 方法來將一個集合中的所有元素新增到另一個集合中,這樣可以更簡潔的實現新增動作,如下所示:
1 2 3 4 5
| public void setNotifyIMap(FileTempRecord record) { List<FileTempRecord> fileTempRecords = new ArrayList<>(); fileTempRecords.add(record); SSE_NOTIFY_IMAP.computeIfAbsent(record.getCreatedBy(), k -> new ArrayList<>()).addAll(fileTempRecords); }
|
這樣,如果 SSE_NOTIFY_IMAP 中已經有對應的 List,就會將 fileTempRecords 中的元素全部加到該 List 中。
綜上所述,我們可以使用下面的程式碼來優化原始程式碼:
1 2 3
| public void setNotifyIMap(FileTempRecord record) { SSE_NOTIFY_IMAP.computeIfAbsent(record.getCreatedBy(), k -> new ArrayList<>()).add(record); }
|
你的鼓勵將被轉換為我明天繼續加班的動力(真的)。 ❤️