簡體   English   中英

番石榴Multimap。把價值放在最后和開始

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

我使用Guava Multimap:

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

此命令將值放在列表的末尾。 但我需要能夠在結束和開始時添加兩者。 有辦法解決這個問題嗎?

鏈接的散列映射不能作為列表工作,因為它只是一個常規映射,其中保留了添加節點的順序,供您稍后使用(例如,使用迭代器)。 這就是為什么你沒有任何函數來添加帶索引的元素。

如果要在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;

add all將所有其他元素添加到newMap,使valueForTheFirstIndex實際上保留在第一個索引中。 請注意,如果執行此操作,您將失去使用映射的優勢,因為如果始終添加到數組的開頭,則復雜性將為O(n ^ 2)。 如果要添加索引,則應在添加內容時使用列表,然后轉換為linkedhashmap以便快速訪問。


(無疑范圍)

你在那里命名為index值不是索引,但實際上是一個鍵。 您沒有地圖中的索引。

actionMap.put(index, "string"); 

正如您可以在文檔中看到的那樣: 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

這不是ListMultimap ,而是SetMultimap 如果需要ListMultimap ,請使用ArrayListMultimapLinkedListMultimap

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM