开发者

Removing a value from a map

I have a Map<Something, List<String>> map. I want to remove a String from the List<String>.

Is that possibl开发者_高级运维e ? 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.


Try map.get(somethingKey).remove("someString").


if you want to remove a String from a particular map item, you should use something like this:

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:

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.

Then you can do something like this:

map.get(mapValue).remove("someString")


Try this: map.get(key).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:

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.

for (List<String> list : map.values()) {
    list.remove("someString");
}


Map<Something, List<String>> myMap = ....;
myMap.get(somethingInstance).remove("someString");


map.values() returns a Collection of 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" );
    }


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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜