user1016403
user1016403

Reputation: 12621

Getting last key from a LinkedHashMap

I have LinkedHashMap returning from DB. From this map I need to get the last key. If I get all keys using keySet method it returns Set of keys but Set does not guarantee the order. I need to take exactly last key from the LinkedHashMap returned from DB. How can I do that ?

Below is the code how I get data from database.

LinkedHashMap<String,String> map = someDao.getMap(String input);

From this map I need to take last key.

Upvotes: 2

Views: 10274

Answers (3)

M. Justin
M. Justin

Reputation: 21123

The last entry of a LinkedHashMap can be easily accessed using the lastEntry() method which was added in Java 21. The last key can be retrieved from this Entry.

LinkedHashMap<String,String> map = someDao.getMap(String input);

Entry<String,String> lastValue = map.lastEntry();
String lastKey = lastEntry.getKey();

Upvotes: 1

AlexR
AlexR

Reputation: 115328

keySet() being executed on LinkedHashMap returns LinkedHashSet that is indeed Set but "remembers" the order of elements.

You can get the last element as following:

Map<TheType> map = .....
.................
TheType theLastKey = new ArrayList<>(map.keySet()).get(map.size() - 1)

Upvotes: 6

DiTap
DiTap

Reputation: 369

Answer from a different post helped me with this answer. Pls refer Java HashMap: How to get a key and value by index? for the original post.

Object myKey = myHashMap.keySet().toArray()[0];

where i have replaced the 0

toArray()[0]  - (where 0 represents the first item in the keyset)

with the size of the keyset

toArray()[(keyset().size)-1] 

Note : Without the -1 at the end, you would get a ArrayIndexOutOfBoundsException.

Upvotes: 0

Related Questions