Why is insertion order not preserved in MultiMap?

被刻印的时光 ゝ 提交于 2019-12-03 12:06:17

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

Multimap<String, String> myMultimap = LinkedListMultimap.create();

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!