需要的时候用什么结构
- 按键排序元素
持有非唯一键的能力
Structure<Integer, String> struct = new Structure<Integer, String>; struct.add(3,"..."); struct.add(1,"John"); struct.add(2,"Edwin"); struct.add(1,"Mary"); struct.toString() == {key-> value;} [1->"John",1->"Mary",2->"Edwin",3->"..."]
最佳答案
如果您想使用标准的 Java API,我会选择 TreeMap<Integer, Set<String>>
.
元素按键排序,因为它是
SortedMap
.来自文档:The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods).
该结构允许使用非唯一键,因为您可以让一个键映射到多个对象。
这种类型的结构称为排序的多映射,并且有几种实现隐藏了第一次插入时创建初始集等的细节。看看Guava或 Apache Commons例如。
根据您的需要,您还可以使用 SortedSet<Pair<Integer, String>>
,其中元素按对中的左侧元素排序。 (请注意,您可能会自己编写 Pair 类,但它不应超过几行。)
关于java - 具有非唯一键的排序映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075872/