how to get the one entry from hashmap without iterating

Viewed 302972

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.

17 Answers

If you are using Java 8 or higher version, you can use this:

return hashMapObject.entrySet().stream().findFirst().orElse(null) // return null if the map is empty

You can use Iterables from Guava.

Iterables.getOnlyElement(map.keySet()); // To fetch the only key
Iterables.getOnlyElement(map.values()); // To fetch the only value
Iterables.getOnlyElement(map.entrySet()); // To fetch the Map.Entry pair
map<string,string>m;
auto it=m.begin();//get iterator to the first element of map(m)
return m->first;//return first string(1st string in map<string,string>m)
//Incase you want the second string 
//you can use return m->second(2st string in map<string,string>m)
//if you want to iterate the whole map you can use loop
for(auto it:m)//m is a map
   cout<<it->first<<endl;

for getting Hash map first element you can use bellow code in kotlin:

val data : Float = hashMap?.get(hashMap?.keys?.first())
Related