views:

344

answers:

3

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). Should there be a method like first() 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 in advance and sorry for my poor grammar.

+8  A: 

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 will entail iterating over the whole entry set.

edit: 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. Commons Collection does not use generics, but you can get a generic-ised version here.

edit: Looks like some buffoon is farting about with the web server on commons.apache.org, it keeps failing requests... I wonder if they're using IIS....

skaffman
A: 
sateesh
A: 

The situation is indeed unfortunate. Here is the (low-priority) feature request that would provide what you need:

http://bugs.sun.com/view%5Fbug.do?bug%5Fid=6266354

Kevin Bourrillion