how to get the one entry from hashmap without iterating

nilesh picture nilesh · Oct 2, 2009 · Viewed 273.6k times · Source

Is there a elegant way of obtaining only one Entry<K,V> from HashMap, without iterating, if key is not known.

As order of entry of entry is not important, can we say something like

hashMapObject.get(zeroth_index);

Although I am aware that there exist no such get by index method.

If I tried approach mentioned below, it would still have to get all the entry set of the hashmap.

for(Map.Entry<String, String> entry : MapObj.entrySet()) {
    return entry;
}

Suggestions are welcome.

EDIT: Please suggest any other Data Structure to suffice requirement.

Answer

Jesper picture Jesper · Oct 2, 2009

Maps are not ordered, so there is no such thing as 'the first entry', and that's also why there is no get-by-index method on Map (or HashMap).

You could do this:

Map<String, String> map = ...;  // wherever you get this from

// Get the first entry that the iterator returns
Map.Entry<String, String> entry = map.entrySet().iterator().next();

(Note: Checking for an empty map omitted).

Your code doesn't get all the entries in the map, it returns immediately (and breaks out of the loop) with the first entry that's found.

To print the key and value of this first element:

System.out.println("Key: "+entry.getKey()+", Value: "+entry.getValue());

Note: Calling iterator() does not mean that you are iterating over the whole map.