简体   繁体   English

番石榴Multimap。把价值放在最后和开始

[英]Guava Multimap. Put value both to the end and beginning

I use Guava Multimap: 我使用Guava Multimap:

Multimap<Integer, String> commandMap = LinkedHashMultimap.create();
...
actionMap.put(index, "string"); // Put value at the end of list.

This command put value at the end of list. 此命令将值放在列表的末尾。 But I need to be able to add both to the end and beginning. 但我需要能够在结束和开始时添加两者。 Is there a way to solve this? 有办法解决这个问题吗?

A linked hashmap doesn't work as a list because it's just a regular map where the order with which the nodes were added is kept, for you to use later (with an iterator for example). 链接的散列映射不能作为列表工作,因为它只是一个常规映射,其中保留了添加节点的顺序,供您稍后使用(例如,使用迭代器)。 That's why you don't have any function to add an element with an index. 这就是为什么你没有任何函数来添加带索引的元素。

If you want to add an element to the beggining of a LinkedHashMultimap you will need to create a new one and add all elements of the old LinkedHashMultimap to the new one: 如果要在LinkedHashMultimap的初始化中添加元素,则需要创建一个新元素并将旧LinkedHashMultimap所有元素添加到新的:

Multimap<Integer, String> newMap = LinkedHashMultimap.create();
newMap.put(key,valueForTheFirstIndex); // first (and only) object of new map
newMap.putAll(commandMap); // adds with the order of commandMap 
commandMap = newMap;

the add all will add all other elements to the newMap making that valueForTheFirstIndex actually stay in the first index. add all将所有其他元素添加到newMap,使valueForTheFirstIndex实际上保留在第一个索引中。 Note that you are loosing the advantages of using a map if you do this, because if always add to the begining of the array your complexity will be O(n^2). 请注意,如果执行此操作,您将失去使用映射的优势,因为如果始终添加到数组的开头,则复杂性将为O(n ^ 2)。 If you want to add to indexes you should use a list while you are adding stuff and then convert to a linkedhashmap for fast accessing. 如果要添加索引,则应在添加内容时使用列表,然后转换为linkedhashmap以便快速访问。


(out of question scope) (无疑范围)

The value that you have there named index is not an index but is actually a key. 你在那里命名为index值不是索引,但实际上是一个键。 You don't have indexes in maps. 您没有地图中的索引。

actionMap.put(index, "string"); 

As you can read in the documentation: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/LinkedHashMultimap.html 正如您可以在文档中看到的那样: http//docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/LinkedHashMultimap.html

put(K key, V value) // you don't see any reference to index there

This isn't a ListMultimap , it's a SetMultimap . 这不是ListMultimap ,而是SetMultimap If you want a ListMultimap , use ArrayListMultimap or LinkedListMultimap . 如果需要ListMultimap ,请使用ArrayListMultimapLinkedListMultimap

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

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