[英]Removing a value from a map
I have a Map<Something, List<String>> map
.我有一个Map<Something, List<String>> map
。 I want to remove a String
from the List<String>
.我想从List<String>
中删除一个String
。
Is that possible?那可能吗? How do I do that?我怎么做?
I don't want to remove the mapping, just alter the 'value' of an entry.我不想删除映射,只需更改条目的“值”。
I have tried map.values().remove("someString")
, but that doesn't seem to work.我试过map.values().remove("someString")
,但这似乎不起作用。
Try map.get(somethingKey).remove("someString")
.试试map.get(somethingKey).remove("someString")
。
if you want to remove a String from a particular map item, you should use something like this:如果你想从一个特定的 map 项目中删除一个字符串,你应该使用这样的东西:
if (map.containsKey(somethingParticular) && map.get(somethingParticular)!=null)
map.get(somethingParticular).remove("someString")
if you want to remove "someString" from all map items, its better to do thw following:如果您想从所有 map 项目中删除“someString”,最好执行以下操作:
for(List<String> list : map.values()) {
if (list!=null)
list.remove("someString");
}
You need to actually have a value to index into the map also.您实际上还需要一个值来索引 map。
Then you can do something like this:然后你可以做这样的事情:
map.get(mapValue).remove("someString")
Try this: map.get(key).remove("someString")试试这个:map.get(key).remove("someString")
map.values()
returns a Collection of List<String>
. map.values()
返回List<String>
的集合。 You have to iterate over the values and search for your key in every list.您必须遍历这些值并在每个列表中搜索您的键。
Map<String, List<String>> map = new HashMap<String, List<String>>();
Collection<List<String>> values = map.values();
for( List<String> list : values ) {
list.remove( "someString" );
}
Do you want to remove the string from all the string lists, or a specific one?您想从所有字符串列表中删除字符串,还是从特定列表中删除?
If you want a specific one, then you need to get the List<String>
by key:如果你想要一个特定的,那么你需要通过键获取List<String>
:
map.get(thekey).remove("someString")
If you want to remove them all, then you need to loop over the values, as they're a collection of List<String>
's.如果要全部删除它们,则需要遍历这些值,因为它们是List<String>
的集合。
for (List<String> list : map.values()) {
list.remove("someString");
}
Map<Something, List<String>> myMap = ....;
myMap.get(somethingInstance).remove("someString");
Yes it is possible:对的,这是可能的:
Map<String,List<Integer>> map = new HashMap<String, List<Integer>>();
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
map.put("intlist",intList);
System.out.println(map.get("intlist"));
intList = map.get("intlist");
intList.remove(1);
intList.add(4);
//they will be the same (same ref)
System.out.println(intList);
System.out.println(map.get("intlist"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.