Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most convenient way to get the last key or value in a LinkedHashMap?

LinkedHashMap description says "it maintains a doubly-linked list running through all of its entries" so I'm wondering how to get the last entry or key entered? Can I confidently downcast .values() to LinkedList to get that doubly-linked list and use .getLast() of that? Or is it an instance of some other Java collection?

I want to stick with java.util if possible.

like image 233
Navigateur Avatar asked Sep 03 '11 11:09

Navigateur


People also ask

How get values from LinkedHashMap?

You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap.

How do I search for a key in LinkedHashMap?

containsKey() method is used to check whether a particular key is being mapped into the LinkedHashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.

Which is faster LinkedHashMap or TreeMap?

LinkedHashMap is faster as compare to TreeMap but is slower than HashMap.


1 Answers

Yes, you can get the last element. But you'll have to look at the suggestions from others to get the last element of the Collection<V> returned by values().

I checked in the source code that the returned values are indeed in the expected order: The AbstactCollection<V> returned by LinkedListMap.values() is backed by an Iterator<V> over the values which is itself directly linked to the Iterator<K> over the keys. And obviously the Iterator<K> over the keys is implemented with the ordered doubly linked list.

like image 153
toto2 Avatar answered Oct 01 '22 15:10

toto2