Search code examples
javadictionarylinkedhashmap

Get first or last entry of a LinkedHashMap


I have used LinkedHashMap because the order in which keys are entered in the map is important.

Now I want to get the value of key in the first position (the first entered entry) or the last position.

Should there be methods 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!


Solution

  • Java 20 and earlier

    The semantics of LinkedHashMap are still those of a Map, rather than that of a LinkedList. 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() }

    However, if you're willing to go beyond the JavaSE API, Apache Commons Collections has its own LinkedMap implementation, which has methods like firstKey and lastKey, which do what you're looking for. The interface is considerably richer.