简体   繁体   中英

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.

Single line solution:

First note that the Java HashMap does not guarantee the order of entries. So each time you iterate over a HashMap, entries appear in different positions. You will need LinkedHashMap that guarantees the predictable iteration order.

Map<String, String> CHILD_NAME_DOB = new LinkedHashMap<>();

Get the key by index:

key = (new ArrayList<>(CHILD_NAME_DOB.keySet())).get(index)

Get the value by index:

CHILD_NAME_DOB.get(key)

Thanks to @Pentium10 for this answer. And I little modified it according to my need.

String key="default";
Iterator myVeryOwnIterator = CHILD_NAME_DOB.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
     key=(String)myVeryOwnIterator.next();
     //String value=(String)meMap.get(key);
     }
Toast.makeText(viewEnterChildExp.getContext(), "Key: "+key , Toast.LENGTH_LONG).show();

I'm getting the last key element by this.

I'll update as soon I also get to find an easy way to key by index.

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;

}

You can also use an ArrayMap instead of a HashMap. To get the value by index use:

ArrayMap.valueAt(index);

To get the Key at an index use:

ArrayMap.keyAt(index);

Fetching the "last" key and fetch by index is not supported by HashMap . You can use a LinkedHashMap and lookup the element with index 2 (or the last element) by iterating over it. But this will be a O(n) operation.

I suggest you use a List<Pair<String, String>> if the order of the keys/values is important to you and you wish to do index based lookup.

If both key based and index based lookup is important to you, you could use a combined data structure that consists of both a List and a HashMap , but note that removal of elements will be O(n) .

You can create a class Child

public class Child(){
private String name;
private String number;

....

}

and then put this object in a List

public static List<Child> CHILD_NAME_DOB = new ArrayList<Child>(); // using LinkedList would defeat the purpose

in this way you can invoke the method get(int index) , that returns the element at the specified position in this list.

In your example

<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>

invoking CHILD_NAME_DOB.get(2) you'll get <neha,05091992> (as Child object)

HashMap does not have a concept of ordering, so getting the n-th entry does not make sense. You could use a TreeMap instead, which is ordered on its keys.

However, you should reconsider your model as you seem to have conflicting interests. On the one hand, accessing by index is typical for Lists , whereas accessing by key is typical for Maps . I'm not sure in which situation you'd want to do both.

If you really want to do both index and key accessing, you could write your own data structure that stores the data in a list combined with a mapping from key to index and vice versa. I would recommend against this, but if that's really what you want, then I think that's the best solution.

I know it is not the best solution, but what about this solution (pseudocode!). Just combine List and Map in one class.

public class UserBirthday {

    private List<String>        names          = new ArrayList<>();
    private Map<String, String> CHILD_NAME_DOB = new HashMap<String, String>();

    public void add(String name, String bd) {

        if (!CHILD_NAME_DOB.containsKey(name)) {
            names.add(name);
        }
        CHILD_NAME_DOB.put(name, bd);

    }

    public String getByName(String name) {
        return CHILD_NAME_DOB.get(name);
    }

    public String getByIndex(int index) {
        return getByName(names.get(index)); // TODO: range test
    }

    public static void main(String[] args) {

        UserBirthday ub = new UserBirthday();
        ub.add("dit", "12345678");
        ub.add("lea", "234239423");
        ub.add("alex", "43534534");
        ub.add("ted", "099098790");

        System.out.println(ub.getByIndex(2));
        System.out.println(ub.getByName("alex"));
    }

}

You may get some problems if you remove an entry, but it should be just a suggestion.

    for (String key : hmList.keySet()) {
        String value = hmList.get(key);

        Log.e("HashMap values", "key=" + key + " ,value=" + value);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM