Jack
Jack

Reputation: 1

How to add List element to map by key?

I use the following approach for sorting items 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"));            
}

However, I cannot add another element for the repeated key value (for example 3) and I think I should implement something like Map<Integer, List<UUID>> map = new TreeMap<>(); rather than Map<Integer, UUID> map = new TreeMap<>();. However, I could not find a proper solution for that. So, how can I manage the repeated key values to be added to the map?

Upvotes: 0

Views: 826

Answers (1)

Mureinik
Mureinik

Reputation: 312289

You could indeed use a Map<Integer, List<UUID>> as you suggested. You can then use computeIfAbsent to create an empty map if the key isn't there, and add the value to the key:

final Map<Integer, List<UUID>> map = new TreeMap<>();

addToMap(int key, String value) {
    mapppp.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

Upvotes: 2

Related Questions