How can I have a HashMap with unique keys in Java?
Or even does this make any sense to have unique keys in HashMap or the keys are unique by default?
I am a newbie.
thx
Hash map key is unique. Add duplicate key, then it will be overwritten.
HashMap hm = new HashMap();
hm.put("1", new Integer(1));
hm.put("2", new Integer(2));
hm.put("3", new Integer(3));
hm.put("4", new Integer(4));
hm.put("1", new Integer(5));// value integer 1 is overwritten by 5
By default Hashmap is not synchronized.
The keys are unique in all maps. The difference between the various maps implementations concern the possibility of null keys, the order of iteration and concurrency issues.
Try to look at the Java API for Map which is interface that HashMap implements. The first sentence is:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
HasMap has unique keys. as .keySet() returns Set which has unique members
HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique.
If you add a key which already exists(collision) in the hashmap, the old value will be replaced.
A generic hashmap is usually implemented as an associative array, so let's say your array has N elements, from 0 to N-1, when you want to add a new (key, value) pair, what it's done behind the scenes is (just conceptually):
index = hash(key) mod N
array[index] = value
So, by construction, a key is mapped to one and one only array entry.
Please note that it's actually a bit more complex than this: I am ignoring on purpose things like collision handling, rehashing, etc, you may have a good general idea here https://en.wikipedia.org/wiki/Hash_table
Related
I basically need to know if my HashMap has different keys that map to the same value. I was wondering if there is a way other than checking each keys value against all other values in the map.
Update:
Just some more information that will hopefully clarify what I'm trying to accomplish. Consider a String "azza". Say that I'm iterating over this String and storing each character as a key, and it's corresponding value is some other String. Let's say I eventually get to the last occurrence of 'a' and the value is already be in the map.This would be fine if the key corresponding with the value that is already in the map is also 'a'. My issue occurs when 'a' and 'z' both map to the same value. Only if different keys map to the same value.
Sure, the fastest to both code and execute is:
boolean hasDupeValues = new HashSet<>(map.values()).size() != map.size();
which executes in O(n) time.
Sets don't allow duplicates, so the set will be smaller than the values list if there are dupes.
Very similar to EJP's and Bohemian's answer above but with streams:
boolean hasDupeValues = map.values().stream().distinct().count() != map.size();
You could create a HashMap that maps values to lists of keys. This would take more space and require (slightly) more complex code, but with the benefit of greatly higher efficiency (amortized O(1) vs. O(n) for the method of just looping all values).
For example, say you currently have HashMap<Key, Value> map1, and you want to know which keys have the same value. You create another map, HashMap<Value, List<Key>> map2.
Then you just modify map1 and map2 together.
map1.put(key, value);
if(!map2.containsKey(value)) {
map2.put(value, new ArrayList<Key>);
}
map2.get(value).add(key);
Then to get all keys that map to value, you just do map2.get(value).
If you need to put/remove in many different places, to make sure that you don't forget to use map2 you could create your own data structure (i.e. a separate class) that contains 2 maps and implement put/remove/get/etc. for that.
Edit: I may have misunderstood the question. If you don't need an actual list of keys, just a simple "yes/no" answer to "does the map already contain this value?", and you want something better than O(n), you could keep a separate HashMap<Value, Integer> that simply counts up how many times the value occurs in the map. This would take considerably less space than a map of lists.
You can check whether a map contains a value already by calling map.values().contains(value). This is not as efficient as looking up a key in the map, but still, it's O(n), and you don't need to create a new set just in order to count its elements.
However, what you seem to need is a BiMap. There is no such thing in the Java standard library, but you can build one relatively easily by using two HashMaps: one which maps keys to values and one which maps values to keys. Every time you map a key to a value, you can then check in amortized O(1) whether the value already is mapped to, and if it isn't, map the key to the value in the one map and the value to the key in the other.
If it is an option to create a new dependency for your project, some third-party libraries contain ready-made bimaps, such as Guava (BiMap) and Apache Commons (BidiMap).
You could iterate over the keys and save the current value in the Set.
But, before inserting that value in a Set, check if the Set already contains that value.
If this is true, it means that a previous key already contains the same value.
Map<Integer, String> map = new HashMap<>();
Set<String> values = new HashSet<>();
Set<Integter> keysWithSameValue = new HashSet<>();
for(Integer key : map.keySet()) {
if(values.contains(map.get(key))) {
keysWithSameValue.add(key);
}
values.add(map.get(key));
}
I would like to know the best data structure used in java suitable for the following senario.
There is a key and a value.
And the key is not duplicated,
Each Value should store collection of objects where the values in each object will change frequently.
Thanks.
HashMap should serve your need.
HashMap allows you to store key value pairs as a collection. HashMap does not allow duplicate keys. You can use different collection to be stored as a value in your HashMap. For example to create a map with keys as a String and value as a list, the define it like this:
Map<String, List<String>> = new HashMap<String, List<String>>();
Also there are implementations for such collection called MultiMap i.e map where a key is associated with collection of values. Two popular implemantations of MultiMap are:
Apacha MultiMap
Guava MultiMap
A type of map. You aren't saying much besides "I need a key-value thingy". If you need to iterate the map by insertion order, there is a LinkedHashMap. If you need to iterate the map by ascending or descending key values, there are sorted maps. If the map will be shared by multiple threads a concurrent map will be useful. If there will be billions of items in the list and you don't mind hemorraghing data (say this is a caching algorithm), a WeakHashMap is for you.
If by "key is not duplicated" you mean it is a violation if a key is inserted if it already exists, you have a few options.
I was doing research on Maps and I discovered that if I add the same key twice deliberately then the size of the Map remains the same. What's the technical reason behind this?
Map map=new HashMap();//HashMap key random order.
map.put("Amit","Java");
map.put("Amit","Java");
Code for retrieving...
System.out.println("There are "+map.size()+" elements in the map.");
System.out.println("Content of Map are...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
}
The result that I get:
There are 1 elements in the map.
Content of Map are...
Amit Java 3943477
Because Map's contract is that keys must be unique. So if you associate a new value to an existing key, it will override the value of the existing entry, not create a new entry:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
You can also check Map#put() javadoc (emphasis mine):
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
A standard Java Map can only have one value per key. Note that that value could be a collection, and thus you can effectively store multiple values per key.
If you want multiple identical keys in a map, various solutions exist. See the Guava Multimap, for example.
If the new key is same as any of the existing keys, then the value in the map is overwritten.
I want to get all the values(multiple) of a particular key.But i m getting only one value?I dont know how to print all the values.Great help if someone correct the code..did not get any help from google search..
import java.util.*;
public class hashing
{
public static void main(String args[])
{
String[] ary=new String[4];
String key;
char[] chrary;
ary[0]=new String("abcdef");
ary[1]=new String("defabc");
ary[2]=new String("ghijkl");
ary[3]=new String("jklghi");
Hashtable<String, String> hasht = new Hashtable<String, String>();
for(int i=0;i<4;i++){
chrary=ary[i].toCharArray();
Arrays.sort(chrary);
key=new String(chrary);
hasht.put(key,ary[i]);
}
Enumeration iterator = hasht.elements();
while(iterator.hasMoreElements()) {
String temp = (String)iterator.nextElement();
System.out.println(temp);
}
}
}
PS:output is defabc jklghi.I want abcdef defabc ghijkl jklghi.
Hashtables can only contain one value per key. To store multiple values, you should either
Store a collection (e.g. List<String> or array) per key. Note that you'll have to initialise the collection prior to insertion of the first value corresponding to that key
Use a MultiMap
Note that many MultiMap implementations exist. The Oracle docs provide a simple implementation too (see here, and search for MultiMap)
The way HashMaps work is that there is only one value for a given key. So if you call:
map.put(key, value1);
map.put(key, value2);
the second line will override the value corresponding to the key.
Regarding your comment about collision, it means something different. Internally, a HashMap stores the key/value pairs in buckets that are defined based on the hashcode of the key (hence the name: hashmap). In the (low probability if the hashcode function is good) case where two non-equal keys have the same hashcode, the implementation needs to make sure that querying the hashmap on one of those keys will return the correct value. That is where hash collision need to be handled.
That's not what collision resolution is meant to do. Collision resolution lets you handle the case when two object with different keys would go into the same "bucket" in the hash map. How this resolution happens is an internal detail of the hash map implementation, not something that would be exposed to you.
Actually, in your case, its not collision, its same key with same hashcode. In general Collision occurs only if two different keys generate same hashcode, This can occur due to a bad implementation of hashCode() method.
Yes, java.util.HashMap will handle hash collisions, If you look at the source code of HashMap, it stores each value in a LinkedList. That means, if two different keys with same hashcode comes in.. then both values will go into same bucket but as two different nodes in the linked list.
Found this link online, which explain How hash map works in detail.
if key is the same, the value will be updated. jvm will not put a new key/value for same keys...
Your Hashtable<String, String> maps one string to one string. So put replaces the value that was before linked to a specific key.
If you want multiple values, you can make a Hashtable<String, []String> or a Hashtable<String, List<String>>.
A cleaner solution would be to use Google's Multimap which allows to associate multiple values to one key :
A collection similar to a Map, but which may associate multiple values
with a single key. If you call put(K, V) twice, with the same key but
different values, the multimap contains mappings from the key to both
values.
You are only putting one String for each key:
hasht.put(key,ary[i]);
So if i=1 that means you put defabc, why do you expect to get multiple values for same key?
Hashtable, like all Map keep only one value per key, the last value you set.
If you want to keep all the values, just print the original array.
String[] ary = "abcdef,defabc,ghijkl,jklghi".split(",");
System.out.println(Arrays.toString(ary));
prints
[abcdef, defabc, ghijkl, jklghi]
I have read somewhere that HashMap uses chaining to resolve collisions. But if that is the case. how can i access all the elements with same key value.
For example :
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1, "1st value");
hmap.put(1, "2nd value");
hmap.put(1, "3rd value");
hmap.put(1, "4th value");
Now, if I do hmap.get(1) it returns “4th Value”
if Indeed it does chaining like
Key values 1 “4th Value” ---> “3rd Value”--->”2nd Value”---->
“1st Value”
How can I get the other values?
hmap.get(1) only returns the 1st value.
My second question is,
if it does linear chaining. How can I remove any one value for a key. suppose I want to remove “4th value” from my hashmap and want to keep all other values for same key, how can i do it?
if I do
hmap.remove(1);
, it removes the complete chain.
HashMap cannot store multiple values for the same key.
Chaining is used to resolve hash collisions, i.e. situations when different keys have the same hash. So, it's not about storing multiple values with the same key, it's about multiple values whose keys have the same hashes.
Data structure that can store multiple values for the same key is called a multimap. Unfortunately, there is no built-in implementation of multimap in JRE.
If you need a multimap, you can maintain a Map of Lists (as suggested by matsev), or use an existing multimap implementation from a third-party library, such as Google Guava.
See also:
Collision resolution
From the documentation of HashMap.put(K, V):
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
What you can do is to put a List as your value, e.g.
HashMap<Integer, List<String>> hmap = new HashMap<Integer, List<String>>();
List<String> list = hmap.get(1);
if (list == null) {
list = new ArrayList<String>();
hmap.put(1, list);
}
list.add("1st value");
list.add("2nd value");
// etc
I don't think HashTable allows duplicate keys. You should read this What happens when a duplicate key is put into a HashMap?
You're obviously looking for a data structure like Guava's MultiMap which allows exactly what you want: Having multiple values per key.
Java's HashMap does not do chaining, as the documentation for put(K, V) clearly states:
public V put(K key, V value)
Associates the specified value with the specified key in this map. If
the map previously contained a mapping for the key, the old value is
replaced.
If you store an existing key in the HashMap then it will override the old value with the new value and put() will return the old value
System.out.println(hmap.put("1",1st value));
System.out.println(hmap); // o/p "1st value"