7

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?

3
  • 2
    You should use Map<Integer, List<String>>. Jun 25, 2013 at 4:56
  • 1
    You can not have duplicate keys in HashMap Jun 25, 2013 at 4:58
  • If you want to store multiple values per key, have a look at MultiMap in the Guava library.
    – Lesleh
    Jun 25, 2013 at 4:59

7 Answers 7

9

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

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

3

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);
}
2

Your key contains only the last value that u put() for a particular key as the values are overwritten for every key and only the last entered value is stored against the key in the Entry object. As per your code your map contains the key value pairs in the following form:

{1=value2, 2=value4, 3=value7}

So, value6 doesnt exist any longer.

2

Looks like you need a set of pairs instead of map.

Set is library class. You can use HashSet for example. Pair is not. You can use http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/tuple/Pair.html

So,

    // init
    Set<Pair<Integer, String>> set = new HashSet<Pair<Integer, String>>();
    set.add(new Pair<Integer, String>(1, "1"));

    // check
    if (set.contains(new Pair<Integer, String>())) {
      ...
    }
2

You can know if a key-pair value exists by getting the value of the desired key and comparing by comparing it to the value.

Example (Java 7 and above):

boolean exists(Map<K,V> map, K key, V value)
{
  return map!=null && map.get(key)!=null && Objects.equals(map.get(key),value);
}

boolean existsinList(Map<K,V> map, K key, V value)
{
  return map!=null && map.get(key)!=null && map.get(key).contains(value);
}

All the necessary checks have been included. One may analyze and remove or modify the conditions (eg. map!=null) to fit things as per their use-case and/or convert this function into a single condition that can fit in any control structure (if needed).

0
1

map stores only unique key and you have stored 3 as key and value6 as value then again 3 as a key and value7 as value then your map conains only 3 as a key and value7 as value value6 will be replaced

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.