user1692517
user1692517

Reputation: 1152

How to add an element into a multiMap?

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

Answers (3)

Boann
Boann

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

Peter Lawrey
Peter Lawrey

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

Elbek
Elbek

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

Related Questions