简体   繁体   English

Java TreeMap不够好

[英]Java TreeMap not good enough

I want to have a Map<Integer, String> that can be sorted out. 我想有一个可以整理的Map<Integer, String> I have tried to use a TreeMap<Integer, String> but it only stores one key per element and I want to have multiple same key elements. 我尝试使用TreeMap<Integer, String>但每个元素仅存储一个键,并且我想拥有多个相同的键元素。
For example, when I add: 例如,当我添加:

map.put(1, "Daniel");
map.put(3, "Monica");
map.put(4, "Pinto");
map.put(3, "Lucia");

and then print all elements, with the TreeMap it appears as: 然后打印所有元素,在TreeMap它显示为:

1 Daniel 1丹尼尔
3 Lucia 3露西亚
4 Pinto 4平托

and I want it to print: 我希望它打印:

1 Daniel 1丹尼尔
3 Monica 3莫妮卡
3 Lucia 3露西亚
4 Pinto 4平托

what datatype should I use for this? 我应该为此使用什么数据类型?

Keys in a map are unique, so you can associate only one value with each key. 映射中的键是唯一的,因此每个键只能关联一个值。 That's why your key "3" appears only once in the output. 这就是为什么键“ 3”在输出中仅出现一次的原因。

There seem to be two solutions, depending on what your requirements are: 根据您的要求,似乎有两种解决方案:

  • Use a SortedSet , using elements compound of an Integer and a String with a custom Comparator . 使用SortedSet ,将IntegerString组成的元素与自定义Comparator That way, "3 Monica" and "3 Lucia" would form completely independent elements of your collection. 这样,“ 3 Monica”和“ 3 Lucia”将构成您收藏中完全独立的元素。 It would match your output in that each element in the collection would be one row in the output shown in your question, but feels kind of clumsy and is most likely not exactly what you want. 它将与您的输出匹配,因为集合中的每个元素在问题中显示的输出中将是一行,但感觉有点笨拙,并且很可能并非您想要的。
  • Use a collection class for your values in the map, eg a List<String> , so you would have a Map<Integer,List<String>> . 使用集合类作为映射中的值,例如List<String> ,这样您将拥有Map<Integer,List<String>> Then, you cannot use the put method to add to that list, but you need to make your own method to lazily retrieve or create the List , and append the new element. 然后,您不能使用put方法将其添加到该列表中,但是需要创建自己的方法来延迟检索或创建List并追加新元素。 The collection would then rather look like this: 然后,该集合将看起来像这样:

    1, [Daniel] 1,[丹尼尔]
    3, [Monica, Lucia] 3,[莫妮卡,露西亚]
    4, [Pinto] 4,[Pinto]

and thus would not match exactly what you asked for but is more likely what you want. 因此不会完全符合您的要求,而更可能是您想要的。

Use MultiMap - a map that holds a collection of values against each key. 使用MultiMap-一个针对每个键保存值集合的映射。

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);

coll will be a collection containing "A", "B", "C". coll将是一个包含“ A”,“ B”,“ C”的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM