Search if specified key and value exists - java

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

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.

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>())) {
...
}

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).

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

Related

Why does my Hashmap<Boolean,String> only have two entries?

I used a HashMap to store a dictionary of type boolean and the indexName value. However I noticed my hashmap only goes up to 2 in size. Why is this happening and how can I fix it?
public Map<Boolean, String> findMetadata(String scanPackage) {
Map<Boolean, String> metadatas = new HashMap<>();
ClassPathScanningCandidateComponentProvider provider = createComponentScanner();
for (BeanDefinition beanDef : provider.findCandidateComponents(scanPackage)) {
try {
Class<?> cl = Class.forName(beanDef.getBeanClassName());
Indexable indexable = cl.getAnnotation(Indexable.class);
logger.info("---------------------------- " + indexable.dictionary() + " " + indexable.indexName());
if (!metadatas.containsValue(indexable.indexName())) {
metadatas.put(indexable.dictionary(), indexable.indexName());
}
} catch (ClassNotFoundException e) {
logger.error(ERROR + e);
}
}
return metadatas;
}
Just change the map declaration in this way:
Map<String, Boolean> metadatas = new HashMap<>();
and the metadata put in this way:
metadatas.put(indexable.indexName(), indexable.dictionary());
Maybe this is what you really want to do.
You are using a Map<Boolean,String> where the key are Boolean and the value String.
Now, Map doesn't supports duplicated keys.
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
So you will be limited with the key, since Boolean can only have 3 values true, false and null... and since HashMap allows null key
This implementation provides all of the optional map operations, and permits null values and the null key
Your maxmimum size will be 3.
It is obvious, you are using Boolean as a key in a hashmap.
Now for Hashmap, below is true.
1. It should have unique keys(Otherwise, It will override the existing value stored corresponding to a key).
and
2. Boolean can have two values either true or false(Can't be null),
so there are only two values in your Map.
If you Want to have a dictionary, you should modify your MAP as below.
Map<Integer, String> metadatas = new HashMap<Integer, String>();
Index: Should be some numbers, So keys are Integer.
Values should be String.

Java Determine If String Starts With Key In Map

I want to determine if a given String startsWith any key in a Map.
The simple solution is to iterate through entire the keySet.
private static Map<String, String> someMap;
private static void method(String line) {
for (String key : someMap.keySet()) {
if (line.startsWith(key)) {
// do something with someMap.get(key);
}
}
}
My question is: Is there is a better data structure to handle this problem?
This can't be done directly with an HashMap: the problem is that HashMap uses an hash calculated on the key to manage its position inside the collection. So there is no way to search for a String key which starts with a specific substring since there is no correlation between two similar String values and their hashes.
But nothing is lost, if you switch to a TreeMap<String,String> the problem can be solved easily. A TreeMap is still an associative container but it stores entries by using a red-black tree in a sorted order.
This means that elements inside a TreeMap are always sorted. In addition to this it gives you some functionalities like:
Map.Entry<K,V> ceilingEntry(K key): Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.
Map.Entry<K,V> floorEntry(K key): Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
Now, not only you can search for a specific key by using a substring of its value, but you also do it in an efficient way. Mind that this works thanks to the implementation of compareTo of String class.
So your problem becomes trivial:
TreeMap<String, Object> map = new TreeMap<String, Object>();
map.put("baz", new Object());
map.put("foo", new Object());
map.put("fooz", new Object());
map.put("fo", new Object());
Map.Entry<String, Object> test = map.ceilingEntry("fo");
bool containsSubStringKey = test != null && test.getKey().startsWith("fo");
TreeMap<String, Object> map = new TreeMap<String, Object>();
map.put("baz", new Object());
map.put("foo", new Object());
map.put("fooz", new Object());
map.put("foor", new Object());
NavigableMap tempMap = list.subMap("foo", true, "fop", false);
//This will return a map of keys that start with "foo". true means inclusive and //false exclusive. "fop" is the first key that does not start with "foo"

What is this Java method doing?

public Map mystery(Map map1, Map map2) {
Map result = new TreeMap();
for (String s1 : map1.keySet()) {
if (map2.containsKey(map1.get(s1))) {
result.put(s1, map2.get(map1.get(s1)));
}
}
return result;
}
map1={bar=1, baz=2, foo=3, mumble=4}; map2={1=earth, 2=wind, 3=air, 4=fire}
For each key in map1 method looks at the corresponding value and of this value exists as a key in map2 than puts it a new TreeMap.
Consider one iteration. map1 has key bar and it's value is 1. Now map2 has 1 as it's key with value earth. So data that is put in new Map is bar:earth and so on..
Also note since resultant map is a TreeMap elements will be stored in Lexicographical order (Since keys are Strings and TreeMap stores elements in sorted order as per keys natural ordering).
It's calculating the composition of the functions map2(map1), along with giving you an impressive number of raw-type warnings.

How to print all the values for a key in HashMap in java

Map<String, String> map = new HashMap<String, String>();
map.put("1", "xyz");
map.put("1", "abc");
map.put("1", "cde");
map.put("2", "err");`
`
for the above map I want to get all the values associated with the key 1. Expected output.
Key:: 1 values are:: xyz, abc, cde
Order of the values doesn't important.
In a Map the key should always be unique. If you associate a new value to an existing key, it will overwrite the value of the existing entry.
You might need to check the interface for Map#put(K, V) method.
If the map previously contained a mapping for the key, the old value
is replaced by the specified value.
So in your case your map will always have "cde" as the value for the key "1".
Use MultiMap
MultiMap mapValue = new MultiValueMap();
mapValue.put("1", "xyz");
mapValue.put("1", "abc");
mapValue.put("1", "cde");
mapValue.put("2", "err");
System.out.println("Map : " + mapValue);
Output: Map : {2=[err], 1=[xyz, abc, cde]}
A map can not have duplicate keys.
If you want to implement what you describe in question. First you need to use multimaps
What you are doing is wrong.
Map doesn't allow duplicates.
So one key -----------> one value
If you see docs of put()
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.)
You can print the values of each key and value like
Ex:
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
In Map you can't have duplicate keys. so In your case final value put for key 1. "cde" will remain in Map
You can do some thing like following to achive what you are expecting
Map<String, List<String>> map = new HashMap<>();
List<String> list=new ArrayList<>();
List<String> list1=new ArrayList<>();
list.add("xyz");
list.add("abc");
list.add("cde");
list1.add("err");
map.put("1", list);
map.put("2",list1);
System.out.println(map.get("1"));
HashMap::put overrides the old value associated with the key. You have to put a List in each map entry and insert new values in the appropriate list.
From the java documentation about HashMap.put(K key, V value) method:
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.
So you can't do that.
This is impossible, a map is called a map because it maps one key value to a value. Multiple keys can map to the same value but not the other way around.
What you probably want is a map which maps to a List<String> instead:
final Map<String, List<String>> map = new HashMap<>();
if (map.get("1") == null) {
map.put("1", new ArrayList<String>());
}
map.get("1").add("xyz");
// ...
A helper function for adding might be convenient
public static <K, V> void add(final K key, final V value, final Map<K, List<V>> map)
{
if (map.get(key) == null) {
map.put(key, new ArrayList<V>());
}
map.get(key).add(value);
}
You can not do this with this type of Map. The key in map must be unique.
To be able to do that you should declare a map, where key is string but values are collections of Strings.
Map<String,Collection<String>> map = new HashMap<String,Collection<String>>();
The to list values from it you can do this
for(String valueOfKey : map.get("key") {
//print or something else
}
Note that to add some values to it you must first check that key is already stored and if not then fist declare a collection.
if(map.contains("key") == false) {
map.put(new ArrayList<String>());
}
map.get("key").add("value");
As this is well know design you might be interest in guava framework and Multimap
The benefit of this class is that it already has implemented the logic how to add and retrieve values from it.
You could do something like:
for (String k : map.keySet())
System.out.println(k);
This would print the keys in the HashMap, but without any guarantees on order.
You can not have duplicate key for a hash map see the below S.O for What happens for duplicate keys in HashMap

How to retrieve all the values associated with a key?

I want to get all the values associated with a key in Map.
For e.g,
Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC");
tempMap.put("2","RR");
tempMap.put("1","RT");
How to retrieve all the values associated with key 1 ?
the thing you must understand is that in a Map, the key is unique.
that means that after
tempMap.put("1","X");
"1" is mapped to "X"
and after
tempMap.put("1","ABC");
"1" is mapped to "ABC" and the previous value ("X") is lost
From the HashMap javadoc:
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.
What you can do is this:
Map<String, List<String>> tempMap = new HashMap<String, List<String>>();
tempMap.put("1", new LinkedList<String>());
tempMap.get("1").add("X");
tempMap.get("1").add("Y");
tempMap.get("1").add("Z");
for(String value : tempMap.get("1")) {
//do something
}
This compartmentalizes values that correspond to the key "1" into their own list, which you can easily access. Just don't forget to initialize the list... else NullPointerExceptions will come to get you.
Yuval =8-)
can't
try using google collections's Multimap
I think you're missing something important:
Map tempMap = new HashMap();
tempMap.put("1","X");
tempMap.put("2","Y");
tempMap.put("3","Z");
tempMap.put("1","ABC"); // replaces "X"
tempMap.put("2","RR"); // replaces "Y"
tempMap.put("1","RT"); // replaces "ABC"
Also, you should use generics where possible, so your first line should be:
Map<String, String> tempMap = new HashMap<String, String>();
To do that you have to associate each key with a Set of values, with corresponding logic to create the set and enter/remove values from it instead of simple put() and get() on the Map.
Or you can use one of the readymade Multimap implementations such as the one in Apache commons.

Categories