java - 具有非唯一键的排序映射

标签 java collections

需要的时候用什么结构

  1. 按键排序元素
  2. 持有非唯一键的能力

    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).

  • 该结构允许使用非唯一键,因为您可以让一个键映射到多个对象。

这种类型的结构称为排序的多映射,并且有几种实现隐藏了第一次插入时创建初始集等的细节。看看GuavaApache Commons例如。

根据您的需要,您还可以使用 SortedSet<Pair<Integer, String>> ,其中元素按对中的左侧元素排序。 (请注意,您可能会自己编写 Pair 类,但它不应超过几行。)

关于java - 具有非唯一键的排序映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075872/

相关文章:

java - 枚举映射和流

java - HashMap 被最后一个值覆盖

python - Pharo 中的高性能 Python 集合

java - 将项目 JRE 构建路径条目设置为 'JavaSE-1.7'

java数组显示最低学生

java - 键绑定(bind)中的修饰符(SHIFT +(随机键))

javascript - 从 JSON 文件渲染主干集合不完全工作

java - 如何从 BufferedImage 中获取 InputStream?

java - 将 jstring 从 jni c 代码发送到接收字符串作为参数的 java 函数

c# - 如何在保存到数据库之前维护唯一列表? - C#