从hashmap中的列表中删除项目 [英] Removing item from a list inside hashmap
问题描述
我在 HashMap
中有一个 List< String>
作为值。键是 String
。当我遍历 HashMap
并从特定键列表中删除项目时,它会更新映射到地图中所有键的列表。
I have an List<String>
in a HashMap
as value. The key is a String
. When I loop through the HashMap
and remove items from the list of a particular key it updates the lists mapped to all the keys in the map.
代码低于
public class ListClass {
public static void main(String[] args) {
ListClass lc = new ListClass();
for(Map.Entry<String, List<String>> entry : lc.postProcessList().entrySet()) {
System.out.println("Date : "+entry.getKey());
List<String> data = entry.getValue();
for (int i = 0; i < data.size(); i++) {
System.out.println(" Value : "+data.get(i));
}
}
}
private Map<String,List<String>> postProcessList() {
Map<String,List<String>> map = new HashMap<String, List<String>>();
populateMap(map);
for(Map.Entry<String, List<String>> entry : map.entrySet()) {
String dateKey = entry.getKey();
System.out.println("Date key : "+dateKey);
List<String> data = entry.getValue();
System.out.println("List before modification : "+data);
for (int i = 0; i < data.size(); i++) {
String dateNoTime = data.get(i).split(" ")[0];
if(!dateNoTime.equalsIgnoreCase(dateKey)) {
System.out.println("Removing : "+data.get(i));
data.remove(i);
}
}
System.out.println("List after modification: "+data+"\n\n");
}
return map;
}
private Map<String,List<String>> populateMap(Map<String,List<String>> map) {
List<String> list = new ArrayList<String>();
list.add("2015-01-13 09:30:00");
list.add("2015-01-12 05:45:10");
list.add("2015-01-13 06:22:12");
list.add("2015-01-12 01:52:40");
list.add("2015-01-12 02:23:45");
map.put("2015-01-12", list);
map.put("2015-01-13", list);
return map;
}
}
在上面的代码中,Map有密钥,一个字符串并保存日期值。列表,即地图的值,包含日期和时间。
In the above code, the Map has key which is a string and holds date values. List, which is the value of the map, holds date and time.
第一个关键是2015-01-12,我正在尝试删除列表中不是2015-01-12的项目。现在两个键中的列表都得到了更新。为什么会这样?
First key is "2015-01-12" and I'm trying to remove the items in the list that are not "2015-01-12". Now the list in both the keys get's updated. Why is that so?
推荐答案
您正在针对两个键向地图添加相同的列表 instance 。因此,当您使用键2015-01-12检索并编辑它时,您将在整个地图中看到更改。
You are adding the same list instance to the map against both keys. Therefore when you retrieve it using key "2015-01-12" and edit it, you'll see the changes in the entire map.
您需要克隆列表在将每个键添加到每个键之前使用 list.clone()
或 new ArrayList< String>(list)
之类的东西。
You need to clone the list using something like list.clone()
or new ArrayList<String>(list)
before you add it to each key.
例如
ArrayList<String> list = new ArrayList<String>();
list.add("2015-01-13 09:30:00");
list.add("2015-01-12 05:45:10");
list.add("2015-01-13 06:22:12");
list.add("2015-01-12 01:52:40");
list.add("2015-01-12 02:23:45");
map.put("2015-01-12", (List<String>)list.clone());
map.put("2015-01-13", (List<String>)list.clone());
这篇关于从hashmap中的列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!