java – 将一对放在LinkedHashMap中的特定位置
发布时间:2020-12-15 05:21:28 所属栏目:Java 来源:网络整理
导读:我想要一个HashMap,按照我添加它们的方式对键进行排序. 所以我使用的是LinkedHashMap.它具有可预测的迭代顺序. 如果使用put,则插入的键将位于地图键集的末尾. 是否可以使用put,将键/对对插入特定位置?例如,我想在索引2处放置一些东西,有效地使这对在迭代时
我想要一个HashMap,按照我添加它们的方式对键进行排序.
所以我使用的是LinkedHashMap.它具有可预测的迭代顺序. 如果使用put,则插入的键将位于地图键集的末尾. 是否可以使用put,将键/对对插入特定位置?例如,我想在索引2处放置一些东西,有效地使这对在迭代时成为第三个条目. 解决方法
下面是一个简单的方法,使用临时映射在适当的索引处理中插入特定索引处的项.
你也可以把它变成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"); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |