Reputation: 1152
I'm using a multimap to sort my words by length. The integer is the word's length. I was wondering how I can add words to the List.
Map<Integer, List<String>> mmap = new HashMap<Integer, List<String>>();
Say I have two words, "bob" and "can" they are both 3 letters. Could someone give me a little pointer on how I would do this?
Upvotes: 0
Views: 1845
Reputation: 50041
With Map.computeIfAbsent
you can create or retrieve the inner collection for a key, and then add to it, in one tidy line:
mmap.computeIfAbsent(word.length(), k -> new ArrayList<>()).add(word);
Upvotes: 3
Reputation: 533590
Using a list of set.
private final List<Set<String>> list = new ArrayList<>();
public void add(String word) {
while(list.size() <= word.length()) list.add(new HashSet<>());
list.get(word.length()).add(word);
}
Upvotes: 0
Reputation: 3484
If(mmap.containsKey(word.length())){
mmap.get(word.length()).add(word);
}else{
List<String> list = new LinkedList<String>;
list.add(word);
mmap.put(word.length(), list)
}
Upvotes: 2