how to get the one entry from hashmap without iterating
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.
The answer by Jesper is good. An other solution is to use TreeMap (you asked for other data structures).
TreeMap<String, String> myMap = new TreeMap<String, String>();
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());
TreeMap has an overhead so HashMap is faster, but just as an example of an alternative solution.
Get values, convert it to an array, get array's first element:
map.values().toArray()[0]
W.
I guess the iterator may be the simplest solution.
return hashMapObject.entrySet().iterator().next();
Another solution (not pretty):
return new ArrayList(hashMapObject.entrySet()).get(0);
Or yet (not better):
return hashMapObject.entrySet().toArray()[0];