I'm facing a problem that seems to have no straighforward solution.
I'm using java.util.Map, and I want to update the value in a Key-Value pair.
Right now, I'm doing it lik this:
private Map<String,int> table = new HashMap<String,int>();
public void update(String key, int val) {
if( !table.containsKey(key) ) return;
Entry<String,int> entry;
for( entry : table.entrySet() ) {
if( entry.getKey().equals(key) ) {
entry.setValue(val);
break;
}
}
}
So is there any method so that I can get the required Entry object without having to iterate through the entire Map? Or is there some way to update the entry's value in place? Some method in Map like setValue(String key, int val)?
jrh
Use
table.put(key, val);
to add a new key/value pair or overwrite an existing key's value.
From the Javadocs:
V put(K key, V value): 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.)
If key is present table.put(key, val) will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key); That's about it
You just use the method
public Object put(Object key, Object value)
if the key was already present in the Map then the previous value is returned.
Related
I have a linked hash map which stores random 6 char string as a key and 30 char string as values. When I call replace method, it is supposed to replace value for given key and return existing value associated with given key.
Code
Map cache = new LinkedHashMap<String, String>();
protected boolean registerCache(String key, String val) {
System.out.println("Registering key "+ key +" associated with : "+val);
String result = cache.put(key, val);
System.out.println("Replacement result "+result);
return result == null;
}
protected synchronized boolean updateCache(String key, String val) {
System.out.println("map before replace : "+cache.toString());
String replaced = cache.replace(key, val);
System.out.println("replacing "+replaced+" with "+val);
return replaced != null;
}
Register cache stores key value for first time and then update method is supposed to replace value for registered key.
But once in 4 times, it fails to replace. It behaves as key was never registered. Here is output:
Registering key \b?}`& associated with : Vtw7vd3Mtk9DEImmZAxfazKrckVpt4
Replacement result null
map before replace: {
d\ZDO<=9pw7cEjdnvWhpbxar564kiSkVpt4Z1,
pHQ)j\=9pw7cEjdnvWhpbxar564kiSkVpt4Z1,
0''nEY=KxE7vdInrD2goNOU5LdMFdEMgsCh-1,
C\Gude=KxE7vdInrD2goNOU5LdMFdEMgsCh-1,
\b?}`&=Vtw7vd3Mtk9DEImmZAxfazKrckVpt4}
replacing null with KxE7vdInrD2goNOU5LdMFdEMgsCh-1
Please suggest if I am doing something wrong. I suspect the key generated should not be random char string.
I figured out reason.
As suggested by Thomas in comment above, I added more sysout for Keys against which value needs to be replaced.
I was using RandomStringUtils.randomAscii(6) (from commons library) for generating key. The key generated had some chars which were printed with spaces and hence the key was not properly found to replace value against it.
When I replaced RandomStringUtils.randomAscii(6) with RandomStringUtils.randomAlphanumeric(8), it's behaving as expected.
According to Java HashMap documentation, put method replaces the previously contained value (if any): https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#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.
The documentation however does not say what happens to the (existing) key when a new value is stored. Does the existing key get replaced or not? Or is the result undefined?
Consider the following example:
public class HashMapTest
{
private static class Key {
private String value;
private Boolean b;
private Key(String value, Boolean b) {
this.value = value;
this.b = b;
}
#Override
public int hashCode()
{
return value.hashCode();
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof Key)
{
return value.equals(((Key)obj).value);
}
return false;
}
#Override
public String toString()
{
return "(" + value.toString() + "-" + b + ")";
}
}
public static void main(String[] arg) {
Key key1 = new Key("foo", true);
Key key2 = new Key("foo", false);
HashMap<Key, Object> map = new HashMap<Key, Object>();
map.put(key1, 1L);
System.out.println("Print content of original map:");
for (Entry<Key, Object> entry : map.entrySet()) {
System.out.println("> " + entry.getKey() + " -> " + entry.getValue());
}
map.put(key2, 2L);
System.out.println();
System.out.println("Print content of updated map:");
for (Entry<Key, Object> entry : map.entrySet()) {
System.out.println("> " + entry.getKey() + " -> " + entry.getValue());
}
}
}
When I execute the following code using Oracle jdk1.8.0_121, the following output is produced:
Print content of original map:
> (foo-true) -> 1
Print content of updated map:
> (foo-true) -> 2
Evidence says that (at least on my PC) the existing key does not get replaced.
Is this the expected/defined behaviour (where is it defined?) or is it just one among all the possible outcomes? Can I count on this behaviour to be consistent across all Java platforms/versions?
Edit: this question is not a duplicate of What happens when a duplicate key is put into a HashMap?. I am asking about the key (i.e. when you use multiple key instances that refer to the same logical key), not about the values.
From looking at the source, it doesn't get replaced, I'm not sure if it's guaranteed by the contract.
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
It finds the existing mapping and replaces the value, nothing is done with the new key, they should be the same and immutable, so even if a different implementation can replace the key it shouldn't matter.
You can't count on this behavior but you should write your code in a way that it won't matter.
When a new pair is added, the map uses hasCode,equals to check if the key already present in the map. If the key already exists the old value is replaced with a new one. The key itself remains unmodified.
Map<Integer,String> map = new HashMap<>();
map.put(1,"two");
System.out.println(map); // {1=two}
map.put(1,"one");
System.out.println(map); // {1=one}
map.put(2,"two");
System.out.println(map); // {1=one, 2=two}
There is an issue with your equals and hashCode contract. ke1 and key2 are identical according to your implementation:
#Override
public boolean equals(Object obj)
{
if (obj instanceof Key)
{
return value.equals(((Key)obj).value);
}
return false;
}
you need to compare Boolean b as well
Key other = (Key) obj;
return value.equals(other.value) && b.equals(other.b);
The same rule apples to hasCode
#Override
public int hashCode()
{
return value.hashCode();
}
return value.hashCode() + b.hashCode();
with these changes key1 and key2 are different
System.out.println(key1.equals(key2));
and the output for your map will be
> (foo-true) -> 1
> (foo-false) -> 2
It is not replaced - neither it should. If you know how a HashMap works and what hashCode and equals is (or more precisely how they are used) - the decision of not touching the Key is obvious.
When you put the other Key/Entry in the map for the second time, that key is first look-up in the map - according to hashCode/equals, so according to the map IFF keys have the same hashCode and are equal according to equals they are the same. If so, why replace it? Especially since if it would have been replaced, that might rigger additional operations or at least additional code to not trigger anything else if keys are equal.
Apparently the current HashSet implementation relies on this HashMap behaviour in order to be compliant to the HashSet documentation.
With that i mean that when you add a new element in an HashSet the documentation says that if you try to add an element in an HasSet that already contains the element, the HashSet is not changed and so the element is not substituted,
In the openjdk8 implementation the HashSet uses an HashMap keys to hold the values and in the HashSet.add method it calls the HashMap.put method to add the value, thus relying on the fact that the put method will not substitute the object
Although this still not a direct specification in the documentation and it's subject to variations in the JRE implementation, it probably provides a stronger
assurance that this will probably not change in the future
I am coding the MapClass right now, but I can't seem to figure out the put method. This is what I have so far:
public V put(K key, V value)
{
for(MapEnt<K,V> x:data)
{
if(x.getKey().equals(key))
{
V reval = x.getValue();
x.setValue(value);
return reval;
}
else
{
}
}
return null;
}
I'm having trouble with what to put in the else to add an entry. I have an ArrayList of keys and values.
Thank you so much!
Nothing (i.e. remove the else part). You don't want to do anything there in case a entry with a appropriate key is found later in the list.
After the loop you need to add a new entry, since you know there is no entry with an appropriate key in the entry list.
BTW: If you want to allow the key to be null, use Objects.equals to check equality instead of calling equals (which may yield a NullPointerException)
There are better ways to do this (the details depend on the type of map you're implementing). However this might be what you're asking for.
// Returns matching value or null if no value exists for this key.
public V put( K key, V value )
{
V existingValue = null;
// The downside of this for each loop is that it will iterate through all
// entries, even if a match is found part way through.
for ( MapEnt<K, V> x : data )
{
if ( x.getKey().equals( key ) )
{
// Match found.
existingValue = x.getValue();
x.setValue( value );
}
}
if ( existingValue == null )
{
// No match was found. add new entry (exactly where you add it will
// Depend on the type of map you are implementing.
}
return existingValue;
}
The following program is printing null. I am not able to understand why.
public class ConcurrentHashMapTest {
public static final Map<String, String> map = new ConcurrentHashMap<>(5, 0.9f, 2);
public static void main(String[] args) {
map.putIfAbsent("key 1", "value 1");
map.putIfAbsent("key 2", "value 2");
String value = get("key 3");
System.out.println("value for key 3 --> " + value);
}
private static String get(final String key) {
return map.putIfAbsent(key, "value 3");
}
}
Could someone help me understand the behavior?
Problem is that by definition putIfAbsent return old value and not new value (old value for absent is always null). Use computeIfAbsent - this will return new value for you.
private static String get(final String key) {
return map.computeIfAbsent(key, s -> "value 3");
}
ConcurrentMap.putIfAbsent returns the previous value associated with the specified key, or null if there was no mapping for the key. You did not have a value associated with "key 3". All correct.
NOTE: Not just for ConcurrentMap, this applies to all implementations of Map.
putIfAbsent() returns the previous value associated with the specified key, or null if there was no mapping for the key, and because key 3 is not present in the map so it returns null.
You have added key 1 and key 2 in the map but key 3 is not associated with any value. So you get a null. Map key 3 with some value and putIfAbsent() will return previous value associated with that key.
Like if map already contained key 3 associated with value A
key 3 ---> A
Then on calling map.putIfAbsent("key 3","B") will return A
This is a frequently asked question, which perhaps suggest this behaviour is unintuitive. Maybe the confusion comes from the way dict.setdefault() works in python and other languages. Returning the same object you just put helps cut a few lines of code.
Consider:
if (map.contains(value)){
obj = map.get(key);
}
else{
obj = new Object();
}
versus:
obj = map.putIfAbsent(key, new Object());
It's in the javadoc:
returns the previous value associated with the specified key, or null if there was no mapping for the key
Please read the documentation of ConcurrentHashMap.putIfAbsent:
Returns:
the previous value associated with the specified key, or null if there was no mapping for the key
As there was no previous value for the key "key 3", it returns null.
If you look at the documentation, it says
Returns: the previous value associated with the specified key, or
null if there was no mapping for the key
In your case, no value was previously associated with the key, hence NULL
The current mapped value could be returned by using merge function. The following could would return the current non-null value if the key already exists, or returns the given new value if a mapping does not exist or if the value is null.
private static String get(final String key) {
return map.merge(key, "value 3", (oldVal, newVal) -> oldVal);
}
or in general:
private T get(final String key, T value) {
return map.merge(key, value, (oldVal, newVal) -> oldVal);
}
This could be useful when you do not prefer to use computeIfAbsent because the mapping function to computeIfAbsent could throw an exception, and you also do not want to do the below:
map.putIfAbsent(key, value);
return map.get(key);
All the answers are correct, and just to add a side note,
If the specified key is not already associated with a value (or is
mapped to null) associates it with the given value and returns null,
else returns the current value.
public V putIfAbsent(K key, V value) {
return putVal(key, value, true); }
The key maintains in the table. The value can be retrieved by calling the get method with a key that is equal to the original key before put. If the key is not found in the table then returns null.
My question might sound silly, but would like to know whether there are any Collection object in Java that does store index,key and values in a single Collection object?
I have the following:
Enumeration hs = request.getParameterNames();
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();
while (hs.hasMoreElements()) {
linkedHashMap.put(value, request.getParameter(value));
}
The above stores key and value in linkedHashMap, but it doesn't have an index. If it has then I could call by index(pos) and get corresponding key and value.
Edit 1
I would want to conditionally check if index(position) is x then get the corresponding key and value pair and construct a string with query.
As mentioned by others, Java collections does not support this. A workaround is Map<R, Map<C, V>>. But it is too ugly to use.
You can go with Guava. It provides a Table collection type. It has the following format Table<R, C, V>. I haven't tried this but I think this will work for you.
Enumeration hs = request.getParameterNames();
Table<Integer, String, String> table = HashBasedTable.create();
while (hs.hasMoreElements()) {
table.put(index, value, request.getParameter(value));
}
Now, if you want key, value pair at, let's say, index 1. Just do table.row(1). Similarly, to get index, value pairs just do table.column(value).
No Collection in java, will support this.
You need to create a new class IndexedMap inheriting HashMap and store the key object into the
arraylist by overriding put method.
here is the answer(answerd by another user: Adriaan Koster)
how to get the one entry from hashmap without iterating
Maybe you need implementing yourself for achieving this functionality.
public class Param{
private String key;
private String value;
public Param(String key, String value){
this.key = key;
this.value = value;
}
public void setKey(String key){
this.key = key;
}
public String getKey(){
return this.key;
}
public void setValue(String value){
this.value = value;
}
public String getValue(){
return this.value;
}
}
Enumeration hs = request.getParameterNames();
List<Param> list = new ArrayList<Param>();
while (hs.hasMoreElements()) {
String key = hs.nextElement();
list.add(new Param(key, request.getParameter(key)));
}
By doing this, you could get param with an index provided by List API.