Java Map Value Comparator,插入时排序 [英] Java Map Value Comparator, sort while inserting

查看:161
本文介绍了Java Map Value Comparator,插入时排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将项目插入到HashMap,TreeMap或SortedMap中(您可以使用值Comparator来建议一些其他api)。



我读过很多帖子,包括这个一个,大多数帖子建议在插入所有项目之后,将HashMap重新插入到具有值Comparator的SortedMap中。



我不想再次重新插入所有值。是否有一个选项或Map类似的数据结构,支持在每次插入后激活一个值比较器?



如果有重复的问题,我会感激一个链接(我已经做了一些搜索,虽然我可能错过了一些)



再次,我有兴趣为某种订购的地图添加一个值,以便所有项目将按照值而不是密钥排序,每次插入后。



Map条目中的值实际上是一个复杂的对象,其中一些getter ,而且我想仅通过值对象上的特定getter进行排序。

解决方案

我有一些解决方法并不完美,并且会使用更多的内存,但是它相当简单。



我可以扩展地图的关键字,也可以保存由getter返回的值值对象,然后我将扩展键比较器按键的右侧元组进行排序。



更新



作为具有非常好表现的魅力。 p>

I would like to insert items into a HashMap, TreeMap or SortedMap (you may suggest some other api) using a value Comparator.

I Have read many posts including this one, most of the posts suggest to re-insert the HashMap into a SortedMap with a value Comparator after all items have been inserted.

I am not interested to re-insert all values again. Isn't there an option or a Map similar data structure which supports the activation of a value Comparator after each insert?

If there is a duplicate issue i would appreciate a link (I have done some search, although I may have missed some)

Again, I am interested in adding a value to some kind of ordered Map so that all items will be ordered by the value and not the key, after each single insert.

The value in the Map entry is actually a complex Object with some getters, and I want to sort only by a specific getter on the value object.

解决方案

I have though of a some workaround , it is not perfect and and will use some more memory, but it rather simple.

I may extend the key of the Map to also hold the value returned by the getter of the Value object, Then i will extend the key Comparator to sort by the right tuple of the key.

UPDATE

Worked as a charm with a very good performance.

这篇关于Java Map Value Comparator,插入时排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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