Search code examples
javadictionarycollectionssetunique

Which Java collection allows unique duplicate keys-value pairs?


I'm trying to write a program to remove duplicate key-value pairs of a word list.

However, a key duplicated with a different value should be allowed to be added.

Which Java collection would solve this situation?

  • key1 aaaa
  • key2 bbbb
  • key3 cccc
  • key4 dddd
  • key2 bbbb - duplicate pair - not allowed
  • key1 hhhh - duplicate key - allowed
  • key5 gggg
  • key2 nnnn

Solution

  • You can do this with a multimap, using a set as the collection for the values, it is fairly simple to make.

    Here is some of the basics of an implementation, not the whole thing but couldn't imagine you would need more than that or maybe a remove method

    Edit

    Just saw you wanted duplicate pairs to be thrown away, can do that using a set, instead of throwing an error just gave back the bool to show if it was there already or not (if it exists returns false)

    public class MultiValueMap<K,V> 
    {
        private final Map<K,Set<V>> mappings = new HashMap<K,Set<V>>();
    
        public Set<V> getValues(K key)
        {
            return mappings.get(key);
        }
    
        public Boolean putValue(K key, V value)
        {
            Set<V> target = mappings.get(key);
    
            if(target == null) 
            {
                target = new HashSet<V>();
                mappings.put(key,target);
            }
    
            return target.add(value);
        }
    
    }