Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is insertion order not preserved in MultiMap?

Tags:

java

multimap

public class MultiMap_Test {
    public static void main(String[] args) {
        Multimap<String, String> myMultimap = ArrayListMultimap.create();

          myMultimap.put("classlabel", "tid");
          myMultimap.put("Y", "1");
          myMultimap.put("Y", "2");
          myMultimap.put("N", "4"); 

          // Iterating over entire MutliMap
          for(String value : myMultimap.values()) {           
              System.out.print(value);
          }
    }
}

The above code prints 1 2 tid 4.

I am not understanding why it is not printing tid 1 2 4.

like image 971
SOUMYADEEP BASU CHOWDHURY Avatar asked Dec 04 '14 20:12

SOUMYADEEP BASU CHOWDHURY


2 Answers

Use LinkedListMultimap instead if you want to keep the insertion order:

Multimap<String, String> myMultimap = LinkedListMultimap.create();
like image 170
Paul Lo Avatar answered Nov 02 '22 07:11

Paul Lo


Why is insertion order not preserved in MultiMap?

In fact, your problem is not with MultiMap but with the selected implementation. ArrayListMultimap uses a HashMap<K, Collection<V>> as implementation of the backing Map<K, Collection<V>>:

public static <K, V> ArrayListMultimap<K, V> create() {
    return new ArrayListMultimap<K, V>();
}

//...

private ArrayListMultimap() {
    super(new HashMap<K, Collection<V>>());
    expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
}

And HashMap doesn't preserve the order of the insertion of the elements.

like image 36
Luiggi Mendoza Avatar answered Nov 02 '22 06:11

Luiggi Mendoza