I am working with hashmap datastructure in java. I have some data in which each entry(value) has a group(key). Now i am storing this data in hashmap as follows
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(1, "value2");
map.put(2, "value3");
map.put(2, "value4");
map.put(3, "value5");
map.put(3, "value6");
map.put(3, "value7");
now I want to search if entry (with key=3 and value="value6") exists in map or not. Is there any specific method to call? or is there and other way to do it?
You can not keep multiple entry against same key in a map. If your map previously contained a mapping for the key, the old value is replaced. You need
Map<Integer,List<String>> map = new HashMap<>();
^^^^^
(Diamond operator)
Where you could save List of string against same key. and you can get the value by map#get
List<String> str = map.get(3);
You can make use of Guava Multimap (API docs)
Its stores the multiple values against one key. For your case ,
Multimap<Integer,String> myMultimap = ArrayListMultimap.create();
myMultimap .put(1, "value1");
myMultimap .put(1, "value2");
myMultimap .put(2, "value3");
myMultimap .put(2, "value4");
myMultimap .put(3, "value5");
myMultimap .put(3, "value6");
myMultimap .put(3, "value7");
This will create the data structure for you
now I want to search if entry (with key=3 and value="value6") exists in map or not. Is there any specific method to call? or is there and other way to do it?
For searching
use multimap#containsEntry(key,value), which return boolean
result based on the result
therefore,
myMultimap.containsEntry(3,"value6")
which will return true
In broad terms: map.get(key)
will retrieve either the value at this key location, or null
if it doesn't exist.
Second, you're actually crushing your values. Maps only ever store one value per key. If you want to store multiple values, consider using another collection as the value, which you can add values into later.
Here's some sample code:
//Declaration - change List to Set if duplicates are annoying
Map<Integer, List<String>> map = new HashMap<>();
//Usage - if the list is empty at the key, new one up. Append the value afterwards.
Integer key = Integer.valueOf(1);
List<String> values = map.get(key);
if(key == null) {
values = new ArrayList<>();
}
values.add("word");
map.put(key, values);
Determining the existence of a value at a particular key becomes easy, too:
public boolean inMap(Map<Integer, List<String>> map, Integer key, String value) {
final List<String> values = map.get(key);
return values != null && values.contains(value);
}
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