Search code examples
javahashmap

Search if specified key and value exists


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?


Solution

  • 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);