Im trying to write program to remove duplicate key-value pairs of a word list. However if key is duplicated with different value, that record should be allowed to add. Please help me to understand Which java collection would be solve this situation.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
Hashtable Features It does not accept duplicate keys. It stores key-value pairs in hash table data structure which internally maintains an array of list. Each list may be referred as a bucket. In case of collisions, pairs are stored in this list.
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);
}
}
You cannot do it by Java collection.
You can use Multimap it supports duplicate keys but it also support duplicate keys and value pairs.
Best solution for you is use Multimap and check if value already exist then dont add it.
To my knowledge, there is no such collection implementation in the default JRE. However, there seem to be implementations in third party libraries.
To get something similar, you can use a Map<K, List<V>>
, which is a map containing a list of values for each key.
However, I do not think that you need this. To merge values for duplicate keys you can check whether the key already exists before you put a new key-value pair into the map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With