Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key from HashMap in Android by position or index

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.

like image 730
DancingMonkeyOnLaughingBuffalo Avatar asked Mar 11 '15 08:03

DancingMonkeyOnLaughingBuffalo


People also ask

Can you access a HashMap by index?

HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.

How do you find the position of a key on a Map?

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.

Can we get key from value in HashMap?

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.

Are maps in Java indexed?

Any map entries containing the specified key name are indexed.


1 Answers

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;

}
like image 72
vishwajit76 Avatar answered Oct 15 '22 11:10

vishwajit76