I have used LinkedHashMap because it is important the order in which keys entered in the map.
But now I want to get the value of key in the first place (the first entered entry) or the last.
Should there be a method like first() and last() or something like that?
Do I need to have an iterator to just get the first key entry? That is why I used LinkedHashMap!
Thanks!
The semantics of
LinkedHashMapare still those of a Map, rather than that of aLinkedList. It retains insertion order, yes, but that’s an implementation detail, rather than an aspect of its interface.The quickest way to get the “first” entry is still
entrySet().iterator().next(). Getting the “last” entry is possible, but will entail iterating over the whole entry set by calling.next()until you reach the last.while (iterator.hasNext()) { lastElement = iterator.next() }edit: However, if you’re willing to go beyond the JavaSE API, Apache Commons Collections has its own
LinkedMapimplementation, which has methods likefirstKeyandlastKey, which do what you’re looking for. The interface is considerably richer.