[英]How to add List element to map by key?
我使用以下方法按鍵對項目進行排序:
final Map<Integer, UUID> map = new TreeMap<>();
while (rowIterator.hasNext()) {
// Add Items to the TreeMap
mapppp.put(1, UUID.fromString("610e9040-840c-48c5-aa64-f193ed896133"));
mapppp.put(2, UUID.fromString("4ff0055d-49a9-4e93-b960-ff70ae1007ce"));
mapppp.put(3, UUID.fromString("751c79ce-445c-406a-9787-a754857a259c"));
mapppp.put(3, UUID.fromString("dc721d77-509d-4bd3-8004-43a8daab5840"));
mapppp.put(3, UUID.fromString("4ca16aff-5a30-4638-8b38-3a93eddb0fc5"));
mapppp.put(3, UUID.fromString("e4be360b-cccb-42a2-b416-eb4bb623b49f"));
}
但是,我不能為重復的鍵值添加另一個元素(例如 3),我認為我應該實現類似Map<Integer, List<UUID>> map = new TreeMap<>();
而不是Map<Integer, UUID> map = new TreeMap<>();
. 但是,我找不到合適的解決方案。 那么,如何管理要添加到地圖中的重復鍵值?
您確實可以按照您的建議使用Map<Integer, List<UUID>>
。 如果鍵不存在,您可以使用computeIfAbsent
創建一個空映射,並將值添加到鍵:
final Map<Integer, List<UUID>> map = new TreeMap<>();
addToMap(int key, String value) {
mapppp.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.