Java LinkedHashMap 获取第一个或最后一个条目 [英] Java LinkedHashMap get first or last entry

查看:106
本文介绍了Java LinkedHashMap 获取第一个或最后一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用过 LinkedHashMap 因为在映射中输入键的顺序很重要.

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

但现在我想首先(第一个输入的条目)或最后一个获取key的值.

But now I want to get the value of key in the first place (the first entered entry) or the last.

是否应该有类似first()last() 之类的方法?

Should there be a method like first() and last() or something like that?

我是否需要一个迭代器来获取第一个键条目?这就是为什么我使用 LinkedHashMap

Do I need to have an iterator to just get the first key entry? That is why I used LinkedHashMap!

谢谢!

推荐答案

LinkedHashMap 的语义仍然是 Map 的语义,而不是 LinkedList 的语义.它保留了插入顺序,是的,但这是一个实现细节,而不是其接口的一个方面.

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.

获得第一个"条目的最快方法仍然是entrySet().iterator().next().获取最后一个"条目是可能的,但需要通过调用 .next() 迭代整个条目集,直到到达最后一个.while (iterator.hasNext()) { lastElement = iterator.next() }

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() }

编辑:但是,如果您愿意超越 JavaSE API,Apache Commons Collections 有自己的 LinkedMap 实现,它有像 firstKeylastKey,它们做了什么您正在寻找.界面相当丰富.

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.

这篇关于Java LinkedHashMap 获取第一个或最后一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆