将一对放在LinkedHashMap中的特定位置

Vol*_*ort 3 java collections

我想要一个HashMap按照我添加它们的方式订购钥匙的地方.

所以我正在使用LinkedHashMap.它具有可预测的迭代顺序.

如果使用put,插入的键将位于地图键集的末尾.

是否可以使用put,将键/对对插入特定位置?例如,我想put索引一些东西2,有效地使这对在迭代时成为第三个条目.

Jea*_*art 12

您可以使用ListOrderedMap阿帕奇百科全书集合.

它有一个put(int index, K key, V value)完全符合你想要的方法.


Bra*_*raj 5

这是一种使用临时映射通过适当的索引处理在特定索引处插入项目的简单方法。

您也可以将其设为Generic

public static void put(LinkedHashMap<String, String> input, 
                                 int index, String key, String value) {

    if (index >= 0 && index <= input.size()) {
        LinkedHashMap<String, String> output=new LinkedHashMap<String, String>();
        int i = 0;
        if (index == 0) {
            output.put(key, value);
            output.putAll(input);
        } else {
            for (Map.Entry<String, String> entry : input.entrySet()) {
                if (i == index) {
                    output.put(key, value);
                }
                output.put(entry.getKey(), entry.getValue());
                i++;
            }
        }
        if (index == input.size()) {
            output.put(key, value);
        }
        input.clear();
        input.putAll(output);
        output.clear();
        output = null;
    } else {
        throw new IndexOutOfBoundsException("index " + index
                + " must be equal or greater than zero and less than size of the map");
    }
}
Run Code Online (Sandbox Code Playgroud)