'Access to the key-value pair of a Map with one element in Java

A method of mine returns a Map<A,B>. In some clearly identified cases, the map only contains one key-value pair, effectively only being a wrapper for the two objects.

Is there an efficient / elegant / clear way to access both the key and the value? It seems overkill to iterate over the one-element entry set. I'm looking for somehing that would lower the brain power required for people who will maintain this, along the lines of:

(...)
// Only one result.
else {
    A leKey = map.getKey(whicheverYouWantThereIsOnlyOne); // Is there something like this?
    B leValue = map.get(leKey); // This actually exists. Any Daft Punk reference was non-intentional.
}

Edit: I ended up going with @akoskm solution's below. In the end, the only satisfying way of doing this without iteration was with a TreeMap, and the overhead made that unreasonable.

It turns out there is not always a silver bullet, especially as this would be a very small rabbit to kill with it.



Solution 1:[1]

If you need both key/value then try something like this:

Entry<Long, AccessPermission> onlyEntry = map.entrySet().iterator().next();
onlyEntry.getKey();
onlyEntry.getValue();

Solution 2:[2]

You can use TreeMap or ConcurrentSkipListMap.

TreeMap<String, String> myMap = new TreeMap<String, String>();
String firstKey   = myMap.firstEntry().getKey();
String firstValue = myMap.firstEntry().getValue();

Another way to use this:

String firstKey   = myMap.firstKey();
String firstValue = myMap.get(myMap.firstKey());

This can work as an alternate solution.

Solution 3:[3]

There is a method called keySet() to get set of keys. read this thread.

else {
    A leKey=map.keySet().iterator().next();

    B leValue; = map.get(leKey); // This actually exists. Any Daft Punk reference was non-intentional.
}

Solution 4:[4]

Using for-each loop and var :

for(var entry : map.entrySet()){
   A key = entry.getKey();
   B value = entry.getValue();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akos K
Solution 2
Solution 3 Community
Solution 4 MWiesner