Using the new collections from Google’s Guava, http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained
How do I loop over a MultiMap for each key in the order of insertion?
For example
multimap = new HashMultiMap<String,String>();
multimap.put("1", "value1");
multimap.put("1", "value2");
multimap.put("1", "value3");
multimap.put("2", "value11");
multimap.put("2", "value22");
multimap.put("2", "value33");
multimap.put("3", "value111");
multimap.put("3", "value222");
multimap.put("3", "value333");
On each loop I need
"value1", "value11", "value111";
then the next loop
"value2", "value22", "value222";
and so on:
"value3", "value33", "value333";
I’m not quite sure what are your needs (or concrete use case), but I’ll try to guess. Other answers suggest using Linked*Multimap or Immutable one, but to get desired output (shown in question) with
Multimapyou will have to create some fancy Map (I’ll discuss this later) or for example create three temporary collections holding first, second and third values for each key (they will be in insertion order, if you use one of suggestedMultimapimplementations). Preferably it would be one ofListMultimapsas you can iterate overmultimap.keySet()to get lists with values available by index:but the downside is that you’ll have to create three Lists for you example what makes this solution rather unflexible. So maybe it’ll be better to put {first,second,third}Values collection to Map>, what brings me to the point:
Maybe you should use Table instead?
Table is designed as A collection that associates an ordered pair of keys, called a row key and a column key, with a single value and, what’s more important here, has row and column views. I’ll use
ArrayTablehere:I deliberately used String for row keys which are [1, 2, 3, …] Integers in fact (like you did in the question) and Integers for column keys starting with 0 ([0, 1, 2, …]) to show similarity to previous example using List’s
get(int)on multimaps values’ collection.Hope this will be helpful, mostly in determining what you want 😉
P.S. I use
ArrayTablehere, because it has neater way of creating fixed set (universe) of rows / keys values thanImmutableTable, but if mutability isn’t required you should use it instead with one change –ImmutableTable(and any other Table implementation) doesn’t havecolumnKeyList()method, but onlycolumnKeySet()which does the same thing, but is slower forArrayTable. And of courseImmutableTable.BuilderorImmutableTable.copyOf(Table)should be used.