简体   繁体   中英

getting last element from a linked hashmap returned from dao layer?

I have LinkedHashMap returning from db. From this map i need to get exactly last element(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 linked hashmap returned from db. how can i do that ?

below is the code how i get data from data base.

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

from this map i need to take last element.

Thanks!

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM