假设我有两个数据结构,一个有序的字符串列表和一个 HashMap。列表看起来像:
types = ["string", "integer", "boolean", "integer"];
HashMap,带有一个对象键和一个字符串值,看起来像:
map = {2=integer, true=boolean, 7=integer, "dog"=string};
重新组织 Map 的“顺序”以使 Map 的值与列表的顺序对齐的最简单/最有效的方法是什么,即 Map 现在在打印时看起来像这样:
map = {"dog"=string, 2=integer, true=boolean, 7=integer};
最佳答案
HashMap
不提供顺序保证。来自documentation :
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
因此,如果您想要一个有序的 Map
,您通常希望从 SortedMap
( documentation) 的实现开始。
不幸的是,SortedMap
按键排序,而您想按值排序,因此您要么必须查看第三方集合库,要么考虑像 LinkedHashMap
( documentation ),它具有可预测的迭代顺序,即使它不维护排序也是如此。
当您的示例显示有两个整数时,您将使用什么策略来决定使用哪个整数?
关于java - 根据 List 的排序重新排序 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52978350/