I have:
public static HashMap<String, String> CHILD_NAME_DOB = new HashMap<>();
Suppose the values in CHILD_NAME_DOB
are:
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
I am trying to fetch the last key element from CHILD_NAME_DOB
. That is, I want to fetch key alisha
from the example above to temporary String name
.
Also I want to know on how to fetch data by index.
Eg.: if int index = 2
, I want key "Neha"
in String name
TIA.
Edit: DateOfBirth value (value data in CHILD_NAME_DOB
) is dynamic and is unknown. So THIS LINK is not what I want.
HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.
You can't. The keys on a Map and a HashMap are not ordered. You'll need to use a structure that preserves order, such as a LinkedHashMap. Note that LinkedHashMap does not provide a method that gets keys by position, so this is only appropriate if you are going to be using an iterator.
Example: Get key for a given value in HashMap Here, the entrySet() method returns a set view of all the entries. Inside the if statement we check if the value from the entry is the same as the given value. And, for matching value, we get the corresponding key.
Any map entries containing the specified key name are indexed.
This way to get key....
public static String getHashMapKeyFromIndex(HashMap hashMap, int index){
String key = null;
HashMap <String,Object> hs = hashMap;
int pos=0;
for(Map.Entry<String, Object> entry : hs.entrySet())
{
if(index==pos){
key=entry.getKey();
}
pos++;
}
return key;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With