哪些 Java 集合(和映射)可以按上次访问进行排序

发布于 2024-09-25 12:13:08 字数 208 浏览 2 评论 0原文

我知道 LinkedHashMap 提供了一个构造函数,您可以在其中指示映射是否应按访问顺序排序,从而有效地提供 LRU 实现。您能告诉我大型收藏动物园中哪些(以及是否)其他收藏和地图提供此功能?

i know that the LinkedHashMap provides a constructor, where you can indicate if the map should be sorted by the access order thus effectively providing an LRU implementation. Can you tell me which (and if) other Collections and Maps from the big Collections zoo provide this feature?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你不是我要的菜∠ 2024-10-02 12:13:08

我认为我不完全理解这个问题,但也许您想看看 LRUMap 实现Commons Collections 框架。

I don't think I completely understand the question, but maybe you want to have a look in the LRUMap implementation of the Commons Collections framework.

洛阳烟雨空心柳 2024-10-02 12:13:08

我认为不存在任何这样的集合或映射(但我刚才也是第一次听说该构造函数)。我已经检查了 Guava,但我认为他们没有也有一个解决方案。

但我认为使用装饰器模式可以轻松实现。编写一个委托对象来实现您想要的接口并将所有方法委托给内部对象。您的包装器还包含一个记录数据访问的 LinkedHashSet / LinkedHashMap (取决于您处理的是集合还是映射)。

现在,您的 iterator() /entrySet() 方法提供了一个视图,该视图首先由 LinkedHashSet/Map 支持,然后由其余数据支持(如果您想反转访问顺序,则反之亦然)。

我将使用类似于 Collections 类中的包装方法来实现它。

例如,

Map<String,String> map = CollectionUtils.viewMapByAccessOrder(
                             new HashMap<String,String>());
List<String> list = CollectionUtils.viewListByAccessOrder(
                             new ArrayList<String>());

这实际上可能是对更多受众有意义的功能。我会考虑在 Guava 项目中提交功能请求。

I don't think any such Collections or Maps exist (but I also heard of that constructor for the first time just now). I have checked Guava, but I don't think they have a solution, either.

But I think it could be easily achieved using the decorator pattern. Write a delegate object that implements the interface you want and delegates all methods to an inner object. Your wrapper also contains a LinkedHashSet / LinkedHashMap (depending on whether you are dealing with a collection or map) that logs data access.

Now your iterator() / entrySet() methods provide a view that's backed first by the LinkedHashSet/Map and then by the rest of the data (or vice-versa if you want to reverse the access order).

I would implement it using wrapper methods like the ones in the Collections class.

E.g.

Map<String,String> map = CollectionUtils.viewMapByAccessOrder(
                             new HashMap<String,String>());
List<String> list = CollectionUtils.viewListByAccessOrder(
                             new ArrayList<String>());

This could actually be functionality that makes sense for a larger audience. I'd consider filing a feature request in the Guava project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文