You can, if instead of Java native HashMap you'll use a Bimap.
It's not the traditional Map implementation, and you need to make sure it's suits your needs.
A bimap (or "bidirectional map") is a map that preserves the
uniqueness of its values as well as that of its keys. This constraint
enables bimaps to support an "inverse view", which is another bimap
containing the same entries as this bimap but with reversed keys and
values.
Using a bimap, you can inverse the view and replace the key.
Checkout both Apache Commons BidiMap and Guava BiMap.
I'd argue the essence of hasmap keys are for index access purposes and nothing more but here's a hack: making a key-wrapper class around the value of the key so the key-wrapper object becomes the hashmap key for index access, so you may access and change key-wrapper object's value for your specific needs:
public class KeyWrapper<T>{
private T key;
public KeyWrapper(T key){
this.key=key;
}
public void rename(T newkey){
this.key=newkey;
}
}
Though you could also have a non existing key be able to get the value of an existing key from the hashmap but I fear it might be criminal, anyways:
public class KeyWrapper<T>{
private T key;
public KeyWrapper(T key){
this.key=key;
}
@Override
public boolean equals(Object o) {
return hashCode()==o.hashCode();
}
@Override
public int hashCode() {
int hash=((String)key).length();//however you want your hash to be computed such that two different objects may share the same at some point
return hash;
}
}
Example
HashMap<KeyWrapper,String> hashmap=new HashMap<>();
KeyWrapper cool_key=new KeyWrapper("cool-key");
KeyWrapper fake_key=new KeyWrapper("fake-key");
hashmap.put(cool_key,"cool-value");
System.out.println("I don't believe it but its: "+hashmap.containsKey(fake_key)+" OMG!!!");