Reputation: 1485
I use 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?
Upvotes: 3
Views: 832
Reputation: 198211
This isn't a ListMultimap
, it's a SetMultimap
. If you want a ListMultimap
, use ArrayListMultimap
or LinkedListMultimap
.
Upvotes: 3
Reputation: 37167
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:
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. 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). 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.
(out of question scope)
The value that you have there named index
is not an index but is actually a key. 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
put(K key, V value) // you don't see any reference to index there
Upvotes: 3